简体   繁体   中英

Java Prime Checker

if found a prime checker in java, which uses this method. Can somebody explain, why the for-loop goes to the square root of the searched prime number? - Is there a more efficient way of doing this? - Thank you!

    public static boolean isPrime(int p){ 
            if(p % 2 == 0 || p < 2){ 
                return false; 
            }  
            else {  
                System.out.println("Sqare: " + (int)Math.sqrt(p));
                for(int i = 3; i <= (int)Math.sqrt(p); i = i+2){ 
                    if(p % i == 0){  
                        return false; 
                    }
                }
            } 

            return true;  
}

If a number is not prime, then it has at least two factors: 63 = 7 x 9 or 121 = 11 x 11 for example. The smaller of the two factors has to be less than or equal to the square root of the original number. If you find any factor, then the number is not prime so you can stop searching once you have found the first factor.

By searching up to and including the square root you are guaranteed to find a factor of a composite number. If the search reaches past the square root without finding a factor, then the number must be prime with factors 1 and the number itself. There is no need to carry on searching beyond the square root as you will not learn anything new and will waste time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM