问题
I am trying hands on validation of whether a BigInteger number entered is a Prime Number or not!
But, it is running fine for smaller numbers like 13,31,but it yields error in the case of 15;by declaring it as a Prime. I am unable to figure-out the mistake,probably it is hidden in the squareroot() method approach involving binary-search!
Please view the code and help me point out the mistake!!!
Calling code :-
boolean p=prime(BigInteger.valueOf(15));
System.out.println("P="+p);
Called code :-
public static boolean prime(BigInteger bi2){
if(bi2.equals(BigInteger.valueOf(2)) || bi2.equals(BigInteger.valueOf(3)))
{
return true;
}
BigInteger bi,bin;
bin=squareroot(bi2);
for(bi=BigInteger.valueOf(2);bi.compareTo(bin)<=0;bi=bi.add(ONE)){
if(bi2.mod(bi).equals(ZERO))
return false;
else continue;
}
return true;
}
public static BigInteger squareroot(BigInteger bi){
BigInteger low,high,mid=ZERO,two;
low=ONE;
high=bi;
two=BigInteger.valueOf(2);
while(low.compareTo(high)<0)
{
mid =(BigInteger)(low.add(high)).divide(two);
//System.out.println("Low-Mid-High="+low+" "+mid+" "+high);
if(mid.multiply(mid).compareTo(bi)==0)
return mid;
if(mid.multiply(mid).compareTo(bi)>0)
high = mid.subtract(ONE);
else if(mid.multiply(mid).compareTo(bi)<0)
low = mid.add(ONE);
}
return mid;
}
回答1:
Your problem is that you return mid
from squareroot
without reevaluating it as (low + high) / 2
. This causes it to return the midpoint of the previous iteration of the algorithm; which is nearly always wrong.
The effect of this is that you sometimes miss some of the prime factors. In the case of 15, because the squareroot
returns 2, you miss finding 3 as a prime factor. In the cases of 13 and 31, there are no prime factors for you to miss, so you get the correct result.
来源:https://stackoverflow.com/questions/23882873/determining-if-a-biginteger-is-prime-in-java