Reputation: 15
My code to get the power of any base with exponent 10 runs okay from 1 to 8: after that the result isn't correct. What did I miss? Please check if the base is 9 or 10?
public static int power(int base, int exponent){
int powResult = 1;
for (int i = 0; i < exponent; i++) {
powResult = powResult * base;
}
return powResult;
}
public static void main(String[] args) {
System.out.println("Enter your x number: ");
Scanner input = new Scanner(System.in);
int x = input.nextInt();
int v1 = power(x, 10);
int result = v1;
System.out.println("your input : "+ x);
System.out.print("your result : "+ result);
Input | Expected output | Printed output |
---|---|---|
7 | 282475249 | 282475249 |
8 | 1073741824 | 1073741824 |
9 | 3486784401 | -808182895 |
10 | 10000000000 | 1410065408 |
Upvotes: 0
Views: 88
Reputation: 341
Remember that the datatype 'int' just can contain values between -2,147,483,648 and 2,147,483,647. So when you assign to the int type 'powResult' a higher value it breaks. Try to define your powResult as a long.
Upvotes: 1
Reputation: 3462
Your problem is that you are using int
which my guess is represented internally as a signed 2^32 value. So in effect the largest value it can represent is 2147483648
9^10 is 3486784401
Upvotes: 1