所以......我在实验室里遇到了一些问题。我已经有一段时间了,但我的计划并没有做我期望它做的事情。我目前正在用Java编写一个Sieve of Eratosthenes程序。不幸的是,它没有给出素数列表的预期输出。我不能,为了我的生活,弄清楚出了什么问题......这里的任何人都可以给我一个指针,指出我可能搞砸了什么吗?
非常感谢!
import java.util.*;
import java.math.*;
public class primeSieve {
/**
* @param args
*/
public static void main(String[] args){
// TODO Auto-generated method stub
Scanner kb = new Scanner(System.in);
//Get user input
System.out.println("Please enter the first number of the set of numbers to calculate primes (first number MUST be prime):");
int first = kb.nextInt();
System.out.println("Please enter the last number of the set of numbers to calculate primes (first number MUST be prime):");
int last = kb.nextInt();
List<Integer> primeList = new ArrayList<Integer>();
List<Integer> numList = new ArrayList<Integer>();
//Make array with values from 2 to the last value entered by user
for(int i = 2; i <= last; i++){
numList.add(i);
}
int size = numList.size();
//Calculate primes
for(int i = 0; i < size; i++)
{
if(i != 0 && i % 2 == 0){continue;} //No point in checking even numbers
if(numList.get(i) == 0){continue;} //If a value has been removed, it's been set to 0. No need to check it.
int prime = numList.get(i); //The current number being worked on. Should be prime
primeList.add(prime); //The number is prime, put it into the prime list.
for(int j = prime; j < size; j += prime) //Loop to remove multiples
{
numList.set(j, 0); //Number is a multiple of the prime previously calculated. Set it to 0, not a prime.
}
}
int primeSize = primeList.size();
System.out.println(primeSize);
System.out.println("The prime numbers from " + first + " to " + last + " are:");
for(int i = first; i < primeSize; i++)
{
System.out.println(primeList.get(i));
}
}
}
编辑:当我查找2到50之间的素数时,程序的输出是:
从2到50的素数是: 7 13 19 25 31 39 43 49
答案 0 :(得分:1)
在嵌套的for
循环中,您可以j
开始prime
。但是,考虑素数2:它位于索引0,而不是索引2.如果你在j
开始prime-first
,事情就应该解决了。另外,正如评论者指出的那样,您的打印循环应该从索引0而不是first
开始。