我试图弄清楚我如何操纵列表,以便找到用户提供的所有素数,我有一个列表步骤,我试图遵循哪些是
创建并填充可能的素数列表
基本上是一个数组列表,其中包含所有数字,直到提供的数字,我已经完成了该部分
为素数创建列表
我有那部分下来
虽然仍然有可能的数字
也就是说,虽然可能的素数列表不是空的。
将可能列表中的第一个数字添加到素数列表中
把那部分也放下了
从可能的素数列表中删除它及其倍数
这就是我开始发呆的地方,我以为我有那个部分,但我得到了一个错误,我不知道为什么。
打印素数
打印素数列表,基本上只是System.out.println(素数);
这是我目前的代码
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class Sieve {
public static void main(String[] args) {
int maxNum;
String howItsGoing, greatDetail;
Scanner scnr = new Scanner(System.in);
Scanner scnr2 = new Scanner(System.in);
// get upper limit
System.out.print("What's the biggest number I should check? ");
maxNum = scnr.nextInt();
// check for verbose mode
System.out.print("Shall I tell you how it's going? ");
howItsGoing = scnr2.nextLine().toUpperCase();
System.out.print("Shall I tell you in great detail? ");
greatDetail = scnr2.nextLine().toUpperCase();
// create and fill list of possible primes
List<Integer> nums = new LinkedList<>();
for (int i = 2; i <= maxNum; i++) {
nums.add(i);
}
// create list for the primes
List<Integer> primes = new ArrayList<>();
// while there are still possible numbers
// add the first number from the list of possibles to the list of primes
for(int i=2; i<=maxNum; i++) {
if(2 % i == 0) {
nums.remove((Integer) i);
primes.add((Integer) i);
}
}
// remove it and its multiples from the list of possible primes
// print the prime numbers
System.out.println("Primes up to " + maxNum);
System.out.println(nums);
System.out.println(primes);
}
}
忽略 howItsGoing 字符串和 greatDetail,我稍后会添加它们。
我如何让这个程序正常工作,其他每个问题都有布尔数组中的解决方案,这不是我想要的。有什么想法吗?
输出
What's the biggest number I should check? 9
Shall I tell you how it's going? n
Shall I tell you in great detail? n
Primes up to 9
[3, 4, 5, 6, 7, 8, 9]
[2]
慕标琳琳
ITMISS
相关分类