我在用java编写代码时遇到了这个问题,这段代码是我为查找质数而实现的。
public class PrimeList {
ArrayList<Integer> list;
public PrimeList(int n){
list = new ArrayList<Integer>();
preparePrimeList(n);
}
private void preparePrimeList(int n){
int c =0;
for (int i=0; i<=n; i++) {
if (i%2!=0 && i%3!=0 && i%5!=0 && i%7!=0) {
list.add(i);
c++;
}
}
list.remove(0);
list.remove(1);
}
public void printPrimeList(){
System.out.println(list);
}
public boolean isPrime(int nbr){
if (list.contains(nbr)) {
return true;
}
return false;
}
public static void main(String[] args) {
PrimeList primes = new PrimeList(100);
primes.printPrimeList();
primes.isPrime(33);
}
}
当我运行代码时,我得到以下代码:
[11, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
为什么我得到错误的输出?输出应该是这样的:
2, 3, 4, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79,
83, 89, 97
false
我做错了什么?
谢谢
发布于 2016-05-22 20:14:16
你的代码完全按照你告诉它的去做。它从11开始的原因是因为你的质数检查有缺陷。例如,2%2 == 0,因此程序认为2不是质数。对于3、5和7也是如此,所以程序从11开始。
您可以通过编写更精确的质数检查方法来避免这种情况,而不是只检查2、3、5或7的可除性。例如:
public boolean checkIfPrime(int num){
for (int x = 2; x < (int)Math.sqrt(num); x++)
if (num % x == 0)
return false;
return true;
}
此外,在尝试从列表中删除第一个项目时,您实际上删除了第一个和第三个项目(因为第三个项目,位置2,移动到第二个项目,位置1)。这就是为什么在你的程序中删除了13。
将list.remove(1)替换为list.remove(0) (这样您就有了两个)。
希望这能有所帮助!
发布于 2016-05-22 20:08:42
问题是i%2!=0 && i%3!=0 && i%5!=0 && i%7!=0
消除了缺少的数字,即2,3,5,7,因为不满足它。
此外,您将删除列表的前两个数字以满足此条件,即1和13。(在删除1之后,11变为索引0)。
但是,如果您的代码最多只能运行到120。在此之后,非质数开始出现在序列中。要计算直到n
的所有质数,您应该改为使用Eratosthene's sieve。
发布于 2016-05-22 20:03:07
这是因为2, 3, 4, 5, 7
不满足您的条件2 % 2 == 0
、3 % 3 == 0
等等。您可以将条件更改为如下所示:
if ((i%2!=0 && i%3!=0 && i%5!=0 && i%7!=0) || i == 2 || i == 3 || i == 5 || i == 7){
....
}
https://stackoverflow.com/questions/37373983
复制相似问题