[英]I do not understand the logic behind this prime number checker (Java)
我不明白这个数字检查器背后的逻辑,我想知道是否有人可以帮助我更好地理解它。
这是代码:
我将尽力评论正在发生的事情,但我不完全了解。
//find prime numbers between 2 and 100
class PrimeNumberFinder {
public static void main(String args[]) {
int i, j; // declare the integer variables "i" and "j"
boolean isPrime; // declare the Boolean variable is prime but do not assign value
// create a for loop that starts at two and stops at 99.
for (i=2; i < 100 ; i++) {
isPrime = true; // I do not know why isPrime is set to true here.
// This is where I get confused badly.. we give the "j" variable a value of two and check to see if it's less than whatever "i" divided by "j" is.
// If "i=2" then how would j (which is = 2) be less than or equal to i/j (2/2)?
for (j = 2; j <= i/j; j++)
if ((i%j) == 0) isPrime = false; // If a certain number goes in evenly that isn't 1, or "i" itself, it isn't prime so we set the boolean to false
if (isPrime) // if true print i
System.out.println(i + " Is a prime number");
}
}
}
如您所见,第二个for循环及其中发生的几乎所有事情都使我感到困惑,尤其是“ j <= i / j”,因为对我而言j总是会变得更大。为什么“ j”甚至会增加? 您不能仅将其除以2并确定它是否是素数?
非常感谢您的帮助,感谢您的阅读。
让我们逐行处理它。
int i, j;
boolean isPrime;
我们首先声明变量。 没什么好看的。
for (i=2; i < 100; i++) {
isPrime = true;
在这里,我们进入循环,该循环基本上包含我们要检查的所有数字(此处为2-99)。 我们还声明,当前数字是质数(除非另有证明)。
for (j = 2; j <= i/j; j++)
if ((i%j) == 0) isPrime = false;
现在,这里就是魔术发生的地方。 我们将检查是否可以将当前数i
平均除以从j == 2
到i/j
的任何整数( i/j
最终只是编写Math.sqrt(i)
)。 那么为什么要一直到那儿呢?
好吧,假设我们有两个因数a
和b
,使得a * b = i
。 现在,如果除数a
大于i
平方根,则另一个除数b
将小于i
平方根。 如果不是,则a * b > i
,这是不可能的。
因此,如果我们找到了可以平均除法的情况,则这显然意味着当前数不是素数,并且将isPrime
变量设置为false
。
if (isPrime) // if true print i
System.out.println(i + " Is a prime number");
}
因此,如果我们仍然具有isPrime == true
,则意味着当前数字经受住了我们的测试,我们可以将其打印出来。
两个进一步的改进;
break;
语句可以添加。 2
是唯一的偶数质数,因此也可以在j == 3
处开始第二个循环,并在每次执行后加2
。 然后,您将不得不分别考虑i == 2
的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.