For Loop 帮助,检查素数
For Loop help, checking prime numbers
for (int i = lo; i <= hi; i++)
{
boolean isPrime = true; // each value of i starts out assuming it IS prime
// Write a loop below that divides i by 2,3,4,5 etc upto i/2
// If at any time you find a divisor that evenly divides i
// Then set isPrime to false
/* your prime checking loop HERE */
for (int j = 2; j <= hi / 2; j++)
{
if (i % j == 0)
{
isPrime = false;
}
}
// DO NOT REMOVE OR MODIFY LINE BELOW
if ( isPrime )
System.out.print( i + " " );
}
好的,这是我目前拥有的代码,我假设问题出在其中。该程序采用文本输入文件并将第一个值设置为 lo(在我的文本演示中,lo = 3 和 hi = 73。)无论出于何种原因,输出为 'prime' 的唯一数字从41 然后就完全没问题了。我不知道为什么前半部分数字根本没有输出。
请记住,我必须为此项目使用 for 循环,方法等目前不在 'vocabulary' 中。尽量保持简单。我会很感激你们的帮助。
再读一遍评论区。它说循环直到 i/2。你循环直到 hi/2.
问题是您继续使用数字本身的模数。
3 % 3 是零,但 3 是质数。
质数校验循环,选其一:
for (int j = 2; j < i / 2; j++)
或
for (int j = 2; j <= sqrt(i); j++)
for (int i = lo; i <= hi; i++)
{
boolean isPrime = true; // each value of i starts out assuming it IS prime
// Write a loop below that divides i by 2,3,4,5 etc upto i/2
// If at any time you find a divisor that evenly divides i
// Then set isPrime to false
/* your prime checking loop HERE */
for (int j = 2; j <= hi / 2; j++)
{
if (i % j == 0)
{
isPrime = false;
}
}
// DO NOT REMOVE OR MODIFY LINE BELOW
if ( isPrime )
System.out.print( i + " " );
}
好的,这是我目前拥有的代码,我假设问题出在其中。该程序采用文本输入文件并将第一个值设置为 lo(在我的文本演示中,lo = 3 和 hi = 73。)无论出于何种原因,输出为 'prime' 的唯一数字从41 然后就完全没问题了。我不知道为什么前半部分数字根本没有输出。
请记住,我必须为此项目使用 for 循环,方法等目前不在 'vocabulary' 中。尽量保持简单。我会很感激你们的帮助。
再读一遍评论区。它说循环直到 i/2。你循环直到 hi/2.
问题是您继续使用数字本身的模数。
3 % 3 是零,但 3 是质数。
质数校验循环,选其一:
for (int j = 2; j < i / 2; j++)
或
for (int j = 2; j <= sqrt(i); j++)