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.

8
  • 2
    Try using public long power(int x, int y) instead Commented Sep 14, 2014 at 16:46
  • What is the largest possible integer value? What is the value of 50^6? en.wikipedia.org/wiki/Integer_overflow Commented Sep 14, 2014 at 16:47
  • Use Long instead of int. int can't store such large reuslt stackoverflow.com/questions/15004944/max-value-of-integer Commented Sep 14, 2014 at 16:50
  • Thanks I understand it now. I'm sorry I'm new to all of this. I feel so dumb now :) Commented Sep 14, 2014 at 16:52
  • 1
    @niana Because an ant can't eat elephant :-) Commented Sep 14, 2014 at 16:52

1 Answer 1

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!
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.