DarkLeafyGreen
DarkLeafyGreen

Reputation: 70466

Calculate the power of 2, java

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

Answers (4)

Vinay Mohaniya
Vinay Mohaniya

Reputation: 1

return (2*zweiHochPositiv(--exponent));

Upvotes: 0

madhurtanwani
madhurtanwani

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

darioo
darioo

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

cdhowie
cdhowie

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

Related Questions