线程 "main" java.lang.ArithmeticException 中的异常:BigInteger 会溢出支持的范围
Exception in thread "main" java.lang.ArithmeticException: BigInteger would overflow supported range
code image
import java.math.BigInteger;
public class GaayuProbOne {
static void power(int N, int P) {
BigInteger result = new BigInteger("10");
BigInteger res = result.pow(P);
System.out.println(res);
}
static double power1(int N, int P) {
double res =Math.pow(N,P);
return res;
}
public static void main(String[] args) {
int N = 10;
double P = 25*power1(10,25);
System.out.println(P);
int q = (int) P;
power(N, q);
}
}
这段代码是计算[=34=中的10251025程序].
如何计算?
Exception in thread "main" java. lang. Arithmetic Exception: Big Integer would overflow supported range
有什么方法可以在[=34中计算10251025 =] 程序?
注意:自发布此答案以来,问题已发生重大变化。它最初要求一种计算 10^25 x 10^25 的方法。
代码有多个问题:
- 它使用了非常规的变量名 - 不是错误,但仍有待修复
power
方法忽略 N
的值
- 您正在无缘无故地执行浮点运算(使用
Math.pow
)
- 你乘以 25,这在你想要实现的目标中没有发生
- 您将一个非常非常大的数字 (25 * 10^25) 投射到
int
,而 int
的最大值仅为 2147483647
- 你试图在最后一行计算 10^2147483647 - 如果没有前面的问题,你将尝试计算 10^(25*10^25),这绝对不是指定的
您实际需要的代码要简单得多:
- 求 10^25,作为
BigInteger
- 乘以它本身
执行此操作的简单代码:
import java.math.BigInteger;
public class Test {
public static void main(String[] args) {
int n = 10;
int p = 25;
BigInteger tmp = BigInteger.valueOf(n).pow(p);
BigInteger result = tmp.multiply(tmp);
System.out.println(result);
}
}
code image
import java.math.BigInteger;
public class GaayuProbOne {
static void power(int N, int P) {
BigInteger result = new BigInteger("10");
BigInteger res = result.pow(P);
System.out.println(res);
}
static double power1(int N, int P) {
double res =Math.pow(N,P);
return res;
}
public static void main(String[] args) {
int N = 10;
double P = 25*power1(10,25);
System.out.println(P);
int q = (int) P;
power(N, q);
}
}
这段代码是计算[=34=中的10251025程序].
如何计算?
Exception in thread "main" java. lang. Arithmetic Exception: Big Integer would overflow supported range
有什么方法可以在[=34中计算10251025 =] 程序?
注意:自发布此答案以来,问题已发生重大变化。它最初要求一种计算 10^25 x 10^25 的方法。
代码有多个问题:
- 它使用了非常规的变量名 - 不是错误,但仍有待修复
power
方法忽略N
的值
- 您正在无缘无故地执行浮点运算(使用
Math.pow
) - 你乘以 25,这在你想要实现的目标中没有发生
- 您将一个非常非常大的数字 (25 * 10^25) 投射到
int
,而int
的最大值仅为 2147483647 - 你试图在最后一行计算 10^2147483647 - 如果没有前面的问题,你将尝试计算 10^(25*10^25),这绝对不是指定的
您实际需要的代码要简单得多:
- 求 10^25,作为
BigInteger
- 乘以它本身
执行此操作的简单代码:
import java.math.BigInteger;
public class Test {
public static void main(String[] args) {
int n = 10;
int p = 25;
BigInteger tmp = BigInteger.valueOf(n).pow(p);
BigInteger result = tmp.multiply(tmp);
System.out.println(result);
}
}