[英]Sieve of Eratosthenes Prime Number Program
在我的实验室中,我被要求编写一个程序,使用Eratosthenes筛子将100以下的质数打印出来。 但是,我已经编写了程序,并且正在打印出许多非素数,例如27,33和99。 不好意思的解释很抱歉,但这是我的代码,我希望有人能提供一些建议或解决方案。 谢谢!
public class SOE {
public static void main(String args[]) {
boolean [] myArray = new boolean[100];
int j=0;
for(int i=0;i<myArray.length;i++) { //Initialises array
myArray[i] = false;
}
for(int i=2;i<myArray.length;i++) { //loops through slot numbers
while(j<myArray.length) { //loops through multiples
if(j%i == 0 || j%5==0) {
myArray[j] = true;
}
j++;
}
}
for(int i=0;i<myArray.length;i++) { //prints out prime numbers
if(myArray[i]==false) {
System.out.println(i);
}
}
}
}
Eratosthenes筛网通常简单得多:
for(int i = 2; i < myArray.length; i++) {
if (myArray[i]) {continue;}
j = 2 * i;
while(j < myArray.length) {
myArray[j] = true;
j += i;
}
}
这将为了消除4, 6, 8, ...
,然后6, 9, ...
,则跳过4
,然后10,...
,则跳过6
...等
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.