Search code examples
javaexponentialexponent

Weird exponentiation error


So, I have this code, which works fine for the first 4 numbers, but then it gives a wrong number, What's the problem? (I know I can also use Math.pow, but I wanted to try doing it myself first)

public static void main(String [] args){

    int number = 98;        
    int result = number;        
    int exponentt = 5;
    int exponent = exponentt--;     
    System.out.println(Math.pow(number, exponent));
    for (int i = 0; i < exponentt ;i++) {
        result = result * number;
        System.out.println(result );            
    }
}

Console: 9604 92236816 449273376


Solution

  • Switch your int number to a long and you will get the right result.

    public static void main(String [] args){
    
        **long** number = 98;        
        **long** result = number;        
        int exponentt = 5;
        int exponent = exponentt--;     
        System.out.println(Math.pow(number, exponent));
        for (int i = 0; i < exponentt ;i++) {
            result = result * number;
            System.out.println(result );            
        }
    }
    

    It's going outside of the range for the int and giving you weird results. int can only store up to 2,147,483,647 -- 98^4 is well over that (9,039,207,968)