Question

So... I have a bit of a problem in a lab. I've been at it for a while, but my program just isn't doing what I'm expecting it to do. I'm currently writing a Sieve of Eratosthenes program in Java. Unfortunately, it's not giving the expected output of a list of primes. I can't, for the life of me, figure out what's wrong... Could anyone here give me a pointer as to where I might have messed something up?

Much thanks!

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));
    }
}       

}

Edit: The output for the program when I look for primes between 2 and 50 is this:

The prime numbers from 2 to 50 are: 7 13 19 25 31 39 43 49

Was it helpful?

Solution

In the nested for loop, you start j at prime. However, consider the prime 2: it is at index 0, not index 2. Things should work out if you start j at prime-first. Also, as a commenter pointed out, your print loop should start at index 0 rather than first.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top