Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2^power without using math.pow and multiplication

Tags:

c++

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;
like image 764
Naman Avatar asked Sep 23 '11 02:09

Naman


2 Answers

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.

like image 90
flight Avatar answered Sep 30 '22 16:09

flight


Check out the ldexp function.

like image 44
Raymond Chen Avatar answered Sep 30 '22 16:09

Raymond Chen