Is there any way to use code 2^power without using math.pow or multiplication operator. So far,
I've though of using 2 counters and additions, but my programs doesn't seem to be working. Here is my work thus far.
int counter=0; // k
int userNumber=0; // p
int power=0;
int sum=0;
cout << "Enter a non-negative number: ";
cin >> userNumber;
while (userNumber > counter)
{
power +=2;
counter++;
power++;
}
sum = power - 1;
// post-condition: Sum = 2^p -1
cout << "The output is " << sum << endl;
return 0;
You can calculate 2^n
with bit-manipulation. Simply do:
1 << n;
This works because left-shifting with binary numbers is equivalent to multiplying by 2.
Check out the ldexp
function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With