public class PrimeNumber02{ public static void main(String [ ] args) { int count = 0; boolean b ; for(int i = 101;i<200;i+=2) { for(int j = 2;j<=Math.sqrt(i);j++) { if(i%j==0){ break;} else{ b=true;} if(b) { count++; System.out.print(i); if(count%5==0) System.out.println(); } } } }}运行结果是:101101101101101101101101101103103......我想要的是:101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 所以上诉的代码错在哪里?
1 回答
已采纳
guozhchun
TA贡献103条经验 获得超76个赞
for (int j = 2; j <= Math.sqrt(i); j++)
{
if (i % j == 0)
{
break;
}
// 从这里以下的代码错了。
// 判断一个数是否是素数需要等这个循环结束后在循环外判断,也就是需要判断是否全不能被这些数整除
// 而不是一个数不能整除就置为true并输出
// 可以模拟程序的运行过程,当j = 2 时,b = true,然后进入if(b)输出结果
// 当j = 3 时, 再次进入if(b)输出结果。
// 如果没有跳出循环,则多次输出结果到循环结束
else
{
b = true;
}
if (b)
{
count++;
System.out.print(i);
if (count % 5 == 0)
System.out.println();
}
}参考的实现代码如下
public class PrimeNumber02
{
public static void main(String[] args)
{
int count = 0;
boolean b;
for (int i = 101; i < 200; i += 2)
{
b = true; // 用于判断是否是素数,如果被某个数整除,则为false,否则为true
for (int j = 2; j <= Math.sqrt(i); j++)
{
if (i % j == 0)
{
b = false;
break;
}
}
if (b)
{
count++;
System.out.print(i + " ");
if (count % 5 == 0)
System.out.println();
}
}
}
}添加回答
举报
0/150
提交
取消
