[英]"WAP a program to find prime numbers between between zero and 100"
I typed this piece of code for finding all the prime numbers between 0 and 100, but it gives output with multiples of other numbers.我输入了这段代码来查找 0 到 100 之间的所有素数,但它给出了其他数字的倍数的输出。 How can I rectify this?我该如何纠正?
public class PrimeNumbers {
public static void main(String[] args) {
int count = 0;
int n = 0;
for (n = 2; count <= 100; n++) {
for (int j = 2; j < n; j++) {
while (n % j == 0) {
j = 2;
n++;
}
}
count++;
System.out.println(n);
}
}
}
Make sure to read the other answers and understand the issue in your code.请务必阅读其他答案并了解代码中的问题。 The error can be fixed with some minor changes:可以通过一些小的更改来修复错误:
public class PrimeNumbers{
public static void main(String[] args) {
for (int n = 2; n <= 100; n++) {
boolean isPrime = true;
for (int j = 2; j < n; j++) {
if (n % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(n);
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.