Im trying to figure out how i would manipulate Lists in order to find all the primes up to a number provided by the user, i have a list steps which im trying to follow which are
create and fill list of possible primes
Basically an arrayList that contains all numbers up to the provided number, i have that part done
create list for the primes
i have that part down
while there are still possible numbers
That is, while the list of possibly-prime numbers is not empty.
add the first number from the list of possibles to the list of primes
Got that part down too
remove it and its multiples from the list of possible primes
this is where i start to daze off a little, i thought i had that part down but im getting an error I dont know why.
print the prime numbers
print the list of prime numbers, essentially just System.out.println(primes);
Heres my code at the moment
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);
}
}
ignore the howItsGoing string and greatDetail, i will add those on later.
How would i get this program to work correctly, every other question has the solution in a boolean array, which is not what i want. Any ideas?
OUTPUT
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]