下面是我检查数字是否为质数的代码。我正在传递大量信息,这就是为什么我使用BigDecimal。
BigDecimal n = new BigDecimal("29331922499794985782735976045591164936683059380558950386560160105740343201513369939006307531165922708949619162698623675349030430859547825708994708321803705309459438099340427770580064400911431856656901982789948285309956111848686906152664473350940486507451771223435835260168971210087470894448460745593956840586530527915802541450092946574694809584880896601317519794442862977471129319781313161842056501715040555964011899589002863730868679527184420789010551475067862907739054966183120621407246398518098981106431219207697870293412176440482900183550467375190239898455201170831410460483829448603477361305838743852756938687673");
//n is not prime
我将所有“假定的”质数发送到ArrayList,我将在以后使用它来计算其他值。这个过程相当快,但是经过将近100次尝试后会出错。我想知道是否有人可以帮助我修复此代码。
/**
* 6a - 1 = prime number
* a = (prime number + 1)/6
*/
public static void isPrime(BigDecimal n)
{
BigDecimal six = new BigDecimal("6");
BigDecimal que = (n.add(one)).remainder(six); //Highlights this spot and says StackOverFlow - null (in java.math.MutableBigInteger)
if(count == 0)
{
System.out.println("True/False: N is prime. " + que.equals(zero) + ", the remainder is " + que); //By the way, this says that the original number is non-prime.
}
else
{
if(que.equals(zero))
{
System.out.println("The number, " + n + " is prime!");
p.add(n);
}
}
count++;
if(n.compareTo(one)== 1)
isPrime(n.subtract(one));
}
答案 0 :(得分:0)
尝试避免递归。由于堆栈的限制,您将获得异常。 或者,您可以增加JVM的Stacksize:
Stack overflows from deep recursion in Java?
要获得更详细的答案,请提供一个可重复的示例。