1

So the recursive function I'm making takes 2 variables (x and y) and calculates x to the power of y. Just like the Math.pow function. y is positive, so I don't need to worry about negative exponents. This is my code:

public static int power(int x, int y) {     
    if (y == 0)         
        return 1;           
    else        
        return x * power(x, y-1);
}

At first it seemed like it worked fine, but then I tried to enter power(50,6). I got -1554869184. Obviously this is wrong because the correct answer can't be negative.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
niana
  • 13
  • 1
  • 5

1 Answers1

2

Your method is good, but it doesn't work for numbers that are too long.

int has 4-bytes (32 bits) => the maximum value is 2147483647 ( 2^31-1 ), total: 2^32 values (there are also some negative numbers)

long has 8-bytes (64 bits) => the maximum value is 9223372036854775807 ( 2^63-1 ), total: 2^64 values

Those values can be found in Java using:

Integer.MAX_VALUE     // Integer and int have the same range
Long.MAX_VALUE        // Long and long have also the same range

For your case: 50^6 = 15625000000 is a valid long number, but not a valid int (it's bigger than 2^32-1 )

Be careful:

If you try to use numbers that are longer you can have problems with long, too. E.g.:

power(10,18);  // OK
power(10,19);  // not OK: negative number
power(10,20);  // not OK: even if the number is positive
               //         the answer is not good - it has only 18 digits!
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199