开发者

2^power without using math.pow and multiplication

开发者 https://www.devze.com 2023-04-06 17:06 出处:网络
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

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;

c开发者_如何学编程out << "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.


   pow = 1;
   while(userNumber > counter){
        pow = pow+pow;
        counter++;
   }
0

精彩评论

暂无评论...
验证码 换一张
取 消