tags:

views:

460

answers:

5

I want a program that takes an int x as parameter and returns 2^x. The implementation is not allowed to use power of.

public int double2 (int x) {
    int r = 2;
    int y = 1;
    for (int i=0; i < x; i++){    
        y = r* y;
    }
    return y;
}

Do you think this is a right solution?

+1  A: 

How about this:

int power = someNumberHere;
int result = 1;
while (power-- > 0) result *= 2;

And I think that is what you want...I think. Are you trying to find a power of two? Maybe expand the question, scope and reasons behind what you want a little.

Robert Massaioli
Please read your code again.
Sinan Ünür
semicolons please ;-)
klez
yes, it can be done like that but how is the compltion >>>> what if I put for loop instead of while??
ss
So what does *power* do in this? I think you want "while (power-- > 0) *= 2"
Clifford
It is far more efficient to do a single bit shift operation than to multiple by 2 several times in a loop.
Adamski
But stupid people chose to close the question for no good reason, so he may never know.
Clifford
A: 
y = x*x;

or

y = x*2;

or

y = 42; // ;)

Depending in what do you mean by the "double of 2".

EDIT

naive implementation

public int 2powerOf( int n ) {
    int r = 2;
    for( int i = 1 ; i < n ; i++ ) {
        r = r * 2;
    }
    return r;
 }

It is almost as the one you posted, this might not handle negative values though.

If you want to know if yours works, then run it and find out for your self.

OscarRyz
i mean 2^2 2^3 2^4 but the power i will add it as veriable
ss
A: 

Does your implementation passes the following JUnit test?

import junit.framework.TestCase;

public class YourClassTest extends TestCase {

    private YourClass sut = new YourClass();

    public void testPowersOfTwo() {
     assertEquals(1, sut.double2(0));
     assertEquals(2, sut.double2(1));
     assertEquals(4, sut.double2(2));
     assertEquals(8, sut.double2(3));
     assertEquals(16, sut.double2(4));
    }

}

If it does, it is a working solution (but maybe not optimal).

Pascal Thivent
+4  A: 

The solution you posted using the for loop produces the right result, but you should look into a more efficient solution (bit shifting) as Adamski first mentioned.

jinsungy
This is the best answer, not only because bit shifting is absolutely the right thing to use here, but because this answer doesn't do the OP's homework for him.
Daniel Pryden
A: 

Just in case if you are needing such kind of explanatory code....(its in c though)

#include <stdio.h>
  int main(void)
 {

   int base, power, index;
   long answer;
   base = 0;
   power = 0;
   answer = 1.00;

   printf(" Enter a base number: ");
   scanf("%d", &base);
   printf(" Enter a power to raise the base to: ");
   scanf("%d", &power);

   for(index = 1; index <= power; index++)
       answer = answer * base;

   printf("%d raised to the power of %d is %ld.", base, power, answer);
   getchar();
   getchar();
   return 0;

}

Ravi