Reputation: 70466
I want to calculate the power of 2 using recursion. Here is my code:
class Aufg1{
public static void main(String args[]){
int erg = zweiHochPositiv(10);
}
public static int zweiHochPositiv(int exponent){
if(exponent > 0)
return (2*zweiHochPositiv(exponent--));
else
return 1;
}
}
I get a lot of errors at
return (2*zweiHochPositiv(exponent--));
but I have no idea what may be wrong.
Upvotes: 0
Views: 2581
Reputation: 1219
I think an efficient way of doing it would be to use the binary representation property of a "power of 2" - its just a bit shift of 1, "exponent" number of times.
Hence, 2^2 = 1 << 2 = (in binary) ....0000 0100 = 4
Upvotes: 1
Reputation: 47213
You need to use prefix version of --
.
This should work:
return (2*zweiHochPositiv(--exponent));
Explanation: exponent--
will never actually lower exponent
's value, so you're calling your recursive function every time with the same value, and that will blow your stack.
--exponent
will lower it's value by one, so you should get desired behaviour.
Upvotes: 5
Reputation: 169488
Replace
return (2*zweiHochPositiv(exponent--));
with
return (2*zweiHochPositiv(exponent - 1));
exponent--
evaluates to the value of the exponent
variable and then decrements it. So when you call zweiHochPositiv(1)
, the method will call zweiHochPositiv(1)
again.
As a result, this method, when called with a value > 0, will recurse indefinitely and ultimately overflow the stack.
Upvotes: 7