Computing the power

I really hope someone can help me with this. How can you compute x to the y power in java without calling any built-in methods from the java class libraries.

I tried doing 2^4 which would be 16 but when I run the program, the answer I get is 6.

Can someone please help me with this.

[302 byte] By [mytimeisnowa] at [2007-10-2 18:26:17]
# 1
If it's an integer power just write a loop. After all, x^y just means "multiply x by itself y times" if y is an integer.%
duffymoa at 2007-7-13 19:47:23 > top of Java-index,Java Essentials,New To Java...
# 2
Assuming that 'y ' is an integer.double result = 1;for (int i=0; i<y; i++) { result = result *
ordinary_guya at 2007-7-13 19:47:23 > top of Java-index,Java Essentials,New To Java...
# 3

You understand why 2^4 is 6, right?

Are you a VB programmer or something? Who told you that x^y means "raise x to the y power"?

^ is the bitwise or operator in Java. If you write out the binary representations of 2 and 4 it'll be obvious why the answer is 6:

2 == 010

4 == 110

2^4 = 110 == 6

Right?

%

duffymoa at 2007-7-13 19:47:23 > top of Java-index,Java Essentials,New To Java...
# 4
I took C++ a while back and if I can remember x^y worked for raising the power of an integer.I just assumed it would work for Java, since some of the syntax is the same as C++.And yes x and y are integers.
mytimeisnowa at 2007-7-13 19:47:23 > top of Java-index,Java Essentials,New To Java...
# 5

> I took C++ a while back and if I can remember x^y

> worked for raising the power of an integer.

No, I don't think so:

http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B

That's the bitwise operator in C/C++, too. You're remembering something else.

>

> I just assumed it would work for Java, since some of

> the syntax is the same as C++.

>

> And yes x and y are integers.

Excellent, you're in luck.

Can't call Math.pow? Or any functions?

It works even for non-integer x. Only the exponent has to be integer for the loop trick to work.

For large exponents it's not very efficient. You can decrease the number of loop iterations by using some tricks. Recursion might help here, too.

%

%

duffymoa at 2007-7-13 19:47:23 > top of Java-index,Java Essentials,New To Java...