1

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

Matt K
  • 6,620
  • 3
  • 38
  • 60
Sander_Blaadjes
  • 159
  • 1
  • 1
  • 10

1 Answers1

0

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)

Xinzz
  • 2,242
  • 1
  • 13
  • 26
  • And in general use java.math.BigInteger because at that rate long can end up very quickly – abc Jul 29 '14 at 14:33