Search code examples
javaprimessieve-of-eratosthenes

sieve of eratosthenes java


I am trying to write a program that implements the sieve of eratosthenes. I can get it from 2 to any given end number but the assignment we are working on asks that we input the starting value. I am completely stuck. I've tried many different codes but it keeps giving me weird answers.

My start is the starting value and end is the ending value. I basically want to find the prime of this range. Thank you!!!

    public static void sieve(int start, int end) {
    int size=(end-start)+1;
    boolean result[]=new boolean[size];
    int prime[]=new int[size];

    for(int i=0; i<size; i++) {
        prime[i]=start+i;
    }


    for(int i=0; i<size; i++) { //every number in result is true
        result[i]=true;
    }

    for(int p=2; p*p <size; p++) {
        if(result[p]==true) {
            for(int i=p*2; i<size; i +=p) {
                result[i]=false;
            }
        }

        for(int i=2; i<size; i++) {
            if(result[i]==true) {
                System.out.print(prime[i] + " ");

            }
        }
    }
}

Solution

  • The Sieve of Eratosthenes works by marking as not prime the multiples of each prime, starting with the first prime number, 2.

    Therefore, even if you are required to find the primes between start and end, you still have to find all the primes between 2 and end. After you do that, just output the primes within the requested range.