【发布时间】:2015-05-03 22:10:47
【问题描述】:
我不明白这个数字检查器背后的逻辑,我想知道是否有人可以帮助我更好地理解它。
代码如下:
我会尽我所能对正在发生的事情发表评论,但我并不完全理解。
//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
非常感谢您的帮助,感谢您的阅读。
【问题讨论】:
-
你遍历所有
is 检查它们是否是 Prime,你首先默认为“是”(true),如果你发现一个j将i分开 - 你将其设置为false。这里的所有都是它的。至于第二个混淆,当i == 2时,第二个循环将不会运行(因为你从 j=2 开始并在 j -
哦,哇,我完全想太多了。我有一个非常愚蠢的印象,即第二个 for 循环必须运行。感谢您的回复。
-
抱歉,我的意思是用类似“i%2 == 0”之类的东西检查两个是否均匀进入
-
所以当“i = 10”归结为循环时,10 被 2 均匀除以所以布尔值返回 false?第二个 for 循环是否总是以“j = 2”开头,所以在第二个循环中运行的所有数字都除以 2 并返回余数?
-
@Jyr - 这绝对是不是埃拉托色尼的筛子。如果
i通过了j = 2的测试,它仍然会检查j = 4(假设i足够大),即使它不可能被4 整除,如果它不能被2 整除。筛子的全部目的是通过排除这种“不可能”的测试来节省时间。还值得指出的是,如果isPrime变为false,内部循环应该立即停止,而不是继续直到j超过i的平方根。