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.
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?
%
> 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.
%
%