Determining if a BigInteger is Prime in Java

旧时模样 提交于 2019-12-25 07:21:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!