In C ++, there is no exponentiation operator. The ^ operator in C ++ means a bitwise exclusive OR operator.
In addition, the output of messages, whether the number is a power of 2, must be moved out of the cycle.
You can use an approach similar to yours, but when the original number is divided by 2, until you get 1 and the remainder of the division will be equal to 0.
Below is a demonstration program.
#include <iostream> int main() { while ( true ) { const unsigned int Base = 2; unsigned int n; std::cout << "Enter a non-negative number (0 - exit): "; if ( not ( std::cin >> n ) || ( n == 0 ) ) break; unsigned int i = 0; unsigned int m = n; while ( m != 1 && m % Base == 0 ) { ++i; m /= Base; } if ( m == 1 ) { std::cout << n << " is equal to " << Base << " in power of " << i << std::endl; } else { std::cout << n << " is not power of " << Base << std::endl; } } return 0; }
The output of the program to the console may, for example, look like this.
Enter a non-negative number (0 - exit): 1 1 is equal to 2 in power of 0 Enter a non-negative number (0 - exit): 2 2 is equal to 2 in power of 1 Enter a non-negative number (0 - exit): 4 4 is equal to 2 in power of 2 Enter a non-negative number (0 - exit): 8 8 is equal to 2 in power of 3 Enter a non-negative number (0 - exit): 16 16 is equal to 2 in power of 4 Enter a non-negative number (0 - exit): 32 32 is equal to 2 in power of 5 Enter a non-negative number (0 - exit): 3 3 is not power of 2 Enter a non-negative number (0 - exit): 4 5 is not power of 2 Enter a non-negative number (0 - exit): 7 7 is not power of 2 Enter a non-negative number (0 - exit): 9 9 is not power of 2 Enter a non-negative number (0 - exit): 0
This approach can be used to check whether a number is a power of some other specified number, that is, not necessarily a two. To do this, it is enough to replace in the program the value of the constant Base with any number at your discretion.
Or you can use the function presented in the noexcept qualifier