0

I am new to Java and when I was trying to find power of number without Math.pow method I realized the answer was not right. And I want to learn why?

public class Main() {

int x = 1919;
int y = x*x*x*x;

public static void main(String[] args) {

System.out.println(y);
}
}

Output: 2043765249

But normally answer is: 13561255518721

ExDet
  • 158
  • 11

3 Answers3

3

You're using an int for the answer, you're getting a numeric overflow.

Use double or long or BigInteger for y and you'll get the right answer.

public class Main {

    public static void main(String[] args) {
        System.out.println(Math.pow(1919, 4));
        System.out.println((double) 1919*1919*1919*1919);
    }
}

Outputs the same value.

MrBorder
  • 359
  • 3
  • 8
3

If you go step by step, you'll see that at a moment the value becomes negative, that's because you reach Integer.MAX_VALUE which is 2^31 -1

int x = 1919;
int y = 1;
for (int i = 0; i < 4; i++) {
    y *= x;
    System.out.println(i + "> " + y);
}

0> 1919
1> 3682561
2> -1523100033
3> 2043765249

You may use a bigger type like double or BigInteger

double x = 1919;

double y = x * x * x * x;
System.out.println(y); // 1.3561255518721E13

BigInteger b = BigInteger.valueOf(1919).pow(4);
System.out.println(b); // 13561255518721
azro
  • 53,056
  • 7
  • 34
  • 70
0

Use long instead of int

public class Main{
    public static void main(String[] args) {
        long x = 1919;
        long y = x*x*x*x;
        System.out.println(y);
    }
}

Read about variables in Java.