Divide by two, then add all the quotients

Mar 13, 2013 at 2:29am
I need to write a program that accepts a number from the user, divides that number by two until it reaches one or cannot be divided evenly anymore, then adds all of the quotients from each division and displays them.
So something like this should be displayed:
Please enter a number: 8
8/2=4
4/2=2
2/2=1
4+2+1= 7

I thought about using an array to possibly store the quotients but I just can't see how that would work.
Any help would be appreciated!
Last edited on Mar 13, 2013 at 5:26am
Mar 13, 2013 at 3:18am
You need a variable to store the total. Use a loop to divide the input by 2 and add the new value of the total for as long as the input is an even number.
To check if a number is even you use the modulo operator, which returns the remainder in a division between integers. A number is even as long as n%2 != 1 (0 is not even).
Mar 13, 2013 at 3:55am
How would I store the quotient after each division and still be able to divide the input by two multiple times?
If I do something like:
1
2
3
4
while (number%2!=1)
{
number=number/2;
}

that would work in dividing the number by two until it is no longer even
However, I would not be able to store the value of each quotient and still be able to divide said quotient by two again until it is no longer even.
Or do you know a way to do so?


Mar 13, 2013 at 5:04am
That's where the variable for the total comes in.
1
2
3
4
5
6
int total = 0;
while (number%2!=1)
{
    number=number/2;
    total += number;
}


Edit: I think I misunderstood the problem. Do oyu need to keep track of all the results of the divisions?
Last edited on Mar 13, 2013 at 5:11am
Mar 13, 2013 at 5:06am
Use a container.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <vector>

int main()
{
    unsigned number = 33554432 ;

    std::vector<unsigned> quotients ;

    while ( !(number%2) )
        quotients.push_back(number /= 2) ;

    for ( auto q : quotients )
        std::cout << q << '\n' ;

    // or, if your compiler doesn't support range-based for loops:
    //for ( std::vector<unsigned>::iterator it = quotients.begin(); it != quotients.end(); ++it )
    //    std::cout << *it << '\n' ;
}
Mar 13, 2013 at 5:21am
Thank you very much!
I never thought it would be that simple, I guess I need to go back to the basics.


I don't need to keep track of them per se, just have them added and the result displayed.
Topic archived. No new replies allowed.