gpt4 book ai didi

java - 有些帮助找出我的埃拉托斯特尼筛出了什么问题

转载 作者:行者123 更新时间:2023-12-01 13:31:07 25 4
gpt4 key购买 nike

所以...我在实验室遇到了一些问题。我已经这样做了一段时间,但我的程序并没有按照我的预期进行。我目前正在用 Java 编写埃拉托斯特尼筛法程序。不幸的是,它没有给出素数列表的预期输出。我一生都无法弄清楚出了什么问题...这里有人能给我指出我可能在哪里搞砸了吗?

非常感谢!

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 的素数是:713192531394349

最佳答案

在嵌套的 for 循环中,您从 prime 处开始 j。但是,考虑素数 2:它位于索引 0,而不是索引 2。如果您在 prime-first 处启动 j,事情应该会成功。另外,正如评论者指出的那样,您的打印循环应该从索引 0 开始,而不是 first

关于java - 有些帮助找出我的埃拉托斯特尼筛出了什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21568476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com