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;
}