My program is a implementation of the Sieve of Eratosthenes algorithm, which finds primes number. It stores two integers up to the maximum, and all odd numbers from 3 upward. It also checks if, for whatever any reason the first number ever reached the square root of the maximum number, all the remaining values from the number list are moved into the primes list. My problem is I keep reaching an error that says
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 1
at java.util.LinkedList.entry(LinkedList.java:365)
at java.util.LinkedList.get(LinkedList.java:315)
at Sieve.sieve(Sieve.java:52)
at Sieve.main(Sieve.java:16)
everytime I enter 25, I get the above runtime error. Here's my code:
// Uses a linked list to implement the Sieve of
// Eratosthenes algorithm for finding prime numbers.
import java.util.*;
public class Sieve {
public static void main(String[] args) {
System.out.println("This program will tell you all prime");
System.out.println("numbers up to a given maximum.");
System.out.println();
Scanner console = new Scanner(System.in);
System.out.print("Maximum number? ");
int max = console.nextInt();
LinkedList<Integer> primes = sieve(max);
System.out.println("Prime numbers up to " + max + ":");
System.out.println(primes);
}
// Returns a list of all prime numbers up to the given maximum
// using the Sieve of Eratosthenes algorithm.
public static LinkedList<Integer> sieve(int max) {
LinkedList<Integer> primes = new LinkedList<Integer>();
// add all numbers from 3 to max to a list
LinkedList<Integer> numbers = new LinkedList<Integer>();
if (max >= 2)
{
numbers.add(2);
for (int i = 3; i <= max; i += 2)
{
numbers.add(i);
}
}
while (!numbers.isEmpty()) {
// remove a prime number from the front of the list
int front = numbers.remove(0);
primes.add(front);
// remove all multiples of this prime number
Iterator<Integer> itr = numbers.iterator();
while (itr.hasNext()) {
int current = itr.next();
if (current % front == 0) {
itr.remove();
}
// If the first number reaches the square root of max, all
// other numbers are moved into the primes list
if (front >= Math.sqrt(max))
{
for(int i = 2; i * i <= max; i++)
{
primes.add(numbers.get(i));
}
}
}
}
return primes;
}
}