简体   繁体   English

Java Prime检查器

[英]Java Prime Checker

if found a prime checker in java, which uses this method. 如果在使用此方法的java中找到了质数检查器。 Can somebody explain, why the for-loop goes to the square root of the searched prime number? 有人可以解释,为什么for循环转到搜索的素数的平方根吗? - 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. 如果数字不是素数,则它至少具有两个因数:例如63 = 7 x 9或121 = 11 x 11。 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. 如果搜索超过平方根而没有找到因数,则该数字必须是因数为1的质数和数字本身。 There is no need to carry on searching beyond the square root as you will not learn anything new and will waste time. 无需进行除平方根之外的搜索,因为您不会学到任何新知识,并且会浪费时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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