### Divide by two, then add all the quotients

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:
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
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).
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:
 1234 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?

That's where the variable for the total comes in.
 123456 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
Use a container.

 12345678910111213141516171819 #include #include int main() { unsigned number = 33554432 ; std::vector 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::iterator it = quotients.begin(); it != quotients.end(); ++it ) // std::cout << *it << '\n' ; }
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.