Java大数的幂计算题

Java power of number calculation problem with big numbers

我是 Java 的新手,当我试图在没有 Math.pow 方法的情况下求数的幂时,我意识到答案是不正确的。我想知道为什么?

public class Main() {

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

public static void main(String[] args) {

System.out.println(y);
}
}

Output: 2043765249

但通常答案是:13561255518721

您正在使用 int 作为答案,您遇到了数字溢出。

y 使用 double 或 long 或 BigInteger,你会得到正确的答案。

public class Main {

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

输出相同的值。

如果你一步一步走,你会看到有那么一刻这个值变成了负数,那是因为你到达了Integer.MAX_VALUE也就是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

您可以使用更大的类型,例如 doubleBigInteger

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

使用long代替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.