简体   繁体   English

在java中找到素数

[英]to find a prime number in java

I came accros one of the solutions for finding if a number is prime as below : 我提出了一种解决方案,以找出数字是否为质数,如下所示:

//checks whether an int is prime or not.
boolean isPrime(int n) {
if (n == 2){
    return true;
}
//check if n is a multiple of 2
if (n%2==0){
    return false;
}
//if not, then just check the odds
for(int i=3;i*i<=n;i+=2) {
    if(n%i==0)
        return false;
}
return true;

} }

What I am trying to understand is this line of code: 我想了解的是以下代码行:

for(int i=3;i*i<=n;i+=2) 

how does 如何

i*i<=n

help in determining that the number is prime ? 帮助确定数字是素数?

Thanks 谢谢

This is a logical rule : there is no point to search for other divisors once you pass the square root because at that point your "new" divisors" will be lower than your square root. 这是一个逻辑规则:一旦通过平方根,就没有必要搜索其他除数,因为在那一刻,您的“新”除数将小于平方根。

Divisors come in pairs: 10 = 2 x 5. Both 2 and 5 are divisors. 除数成对出现:10 = 2 x5。2和5均为除数。 In each pair one is <= the square root, and the other is >= the square root. 在每对中,一个是<=平方根,另一个是> =平方根。 2 <= sqrt(10); 2 <= sqrt(10); 5 >= sqrt(10). 5> = sqrt(10)。 Once you have found the 2, there is no need to carry on searching for the 5. 5 = 10 / 2. 找到2之后,就无需继续搜索5。5 = 10/2。

eg : 100 : you check for 2,3,5,7,9, and you stop because if you check for next one (11), 100/11 is 9 and you already checked for 9. You stop at the square root. 例如:100:您检查2,3,5,7,9,然后停止,因为如果您检查下一个(11),则100/11是9,而您已经检查了9。您在平方根处停止。

If you find all divisors(including the primes) of n are say a,b,c,d...h. 如果找到n的所有除数(包括质数),则说a,b,c,d ... h。

If a divisor h > sqrt(n) exists, then some divisor c must also exist such that 如果除数h> sqrt(n)存在,那么也必须存在一些除数c,使得

h * c = n
and since h > sqrt(n) and h * c = sqrt(n) * sqrt(n)
c < sqrt(n).

So, if a divisor greater than sqrt(n) exists than a divisor less than sqrt(n) must also exist and should be able to break the loop before it counts beyond sqrt(n). 因此,如果存在除数大于sqrt(n)的除数,小于除数小于sqrt(n)的除数也必须存在,并且应该能够打破循环,直到其计数超过sqrt(n)。 So, we don't need to count beyond sqrt(n), hence the condition 因此,我们不需要计算超出sqrt(n)的值,因此条件

i*i < n

is imposed. 被强加。

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

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