我有两个简单的 java 代码。第一个将恒功率定义为 power = a.pow(b);
import java.math.BigInteger;
public class FermatOne
{
public static void main(String[] args)
{
BigInteger a = new BigInteger ("2");
BigInteger k = new BigInteger ("15");
BigInteger c = new BigInteger ("1");
int b = 332192810;
BigInteger n = new BigInteger ("2");
BigInteger power;
power = a.pow(b);
BigInteger exponent;
exponent = k.multiply(power);
BigInteger mod;
mod = exponent.add(c);
BigInteger result = n.modPow(exponent,mod);
System.out.println("Result is ==> " + result);
}
}
第二个将恒功率定义为 power = BigInteger.ONE.shiftLeft(b)
import java.math.BigInteger;
public class FermatOne
{
public static void main(String[] args)
{
BigInteger k = new BigInteger ("15");
BigInteger c = new BigInteger ("1");
int b = 332192810;
BigInteger n = new BigInteger ("2");
BigInteger power;
power = BigInteger.ONE.shiftLeft(b);
BigInteger exponent;
exponent = k.multiply(power);
BigInteger mod;
mod = exponent.add(c);
BigInteger result = n.modPow(exponent,mod);
System.out.println("Result is ==> " + result);
}
}
在命令行中设置内存标志 -Xmx1024m 第一个代码工作正常,但对于第二个代码我收到错误:java.lang.OutOfMemoryError :Java heap space
我的问题:我应该在第二个代码中更改什么以避免 java.lang.OutOfMemoryError?
最佳答案
您正在尝试计算类似 2 ^ (15 * 2 ^ 332192809)
的数字。我不知道你能不能在宇宙中容纳这样的数字!!或者,答案可能只是... 42
? ;-)
更严重的是,您在计算这个数字时真的会遇到麻烦。以位编码,15 * 2 ^ 332192810
本身将需要近 1 GB。然后再次将2
提升到那个次方,我不想知道...
更严重的是,当您深入研究 java.math.BigInteger
的实现时,我认为您只是遇到这样的错误 faster shift,因为它比幂方法更有效地实现。话虽如此,您是否尝试过使用 System.gc()
在您的代码中强制执行垃圾回收?
更新:我最初的推理可能是错误的。 2 ^ 332192809
可以用1GB来计算。总体结果可能会被 java.math.BigInteger
有效地“修改”,尽管我相信这个计算可能需要一段时间......
关于java - 如何避免 java.lang.OutOfMemoryError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8429797/