Coding Interview Club

Prepare for coding interviews in simple and structured steps

Explaining Sieve of Eratosthenes Algorithm for Finding all Prime Numbers Up To Any Given Limit

In mathematics, the sieve of Eratosthenes is an algorithm for finding all prime numbers up to any given limit.

It does so by iteratively marking as composite (i.e., not prime) the multiples of each prime, starting with the multiples of 2.

It works on the principle that all non-prime numbers are divisible by a prime number.

The sieve of Eratosthenes is one of the most efficient ways to find all of the smaller primes. It is named after Eratosthenes of Cyrene; the sieve was described and attributed to Eratosthenes in the Introduction to Arithmetic by Nicomachus.

 

Algorithm

Steps

  1. Initialize a boolean array of size max-size + 1 with true. 
    • We will need to find the prime including max-size. array[max-size] is in the location max-size + 1.
  2. Get every prime and cross off all multiples of it as false.
    • Cross off can start from the square(current prime) as all elements less than prime would have already crossed off.
    • We will have a count of elements that are crossed off and later we will create the primes array with this size.
      • The count is incremented only if this is the first time we are crossing off. For example, numbers such as 90 are multiples of both 2 and 3.

 

Implementation (Java)

Below is the static method that performs the algorithms:

public class SieveOfEratosthenes {

  // Implementation of Sieve Of Eratosthenes
  // that return a prime array
  static int[] sieveOfEratosthenes(int max) {
    boolean[] flags = new boolean[max + 1];

    initBooleanArray(flags, true);

    int primesCount = max + 1;

    int prime = 2;

    while (prime <= max) {
      int crossedOff = crossOff(flags, prime);

      primesCount = primesCount - crossedOff;

      prime = getNextPrime(flags, prime);

      if (prime >= flags.length)
        break;
    }

    // Copying primes to prime array
    int[] primes = new int[primesCount - 2];
    int count = 0;
    for (int i = 2; i <= max; i++) {
      if (flags[i]) {
        primes[count] = i;
        count++;
      }
    }

    // Returning primes array
    return primes;
  }

Above method used the below private methods:

  // Private method used by sieveOfEratosthenes
  // to cross off non-primes that are multiples of current prime
  private static int crossOff(boolean[] flags, int prime) {
    int crossedOff = 0;

    for (int i = prime * prime; i < flags.length; i = i + prime) {
      if (flags[i] != false) {
        flags[i] = false;
        // increment count only if this is the firt time
        // 90 may come twice as it is multiple of 2 and 3.
        crossedOff++;
      }

    }
    return crossedOff;
  }

  // Private method used by sieveOfEratosthenes
  // to get the next prime
  private static int getNextPrime(boolean[] flags, int current) {
    int next = current + 1;

    while (next < flags.length && flags[next] == false) {
      next++;
    }

    return next;
  }

Below is an utility method for initializing a boolean array:

  // Utility method for initializing a boolean array
  static void initBooleanArray(boolean[] arr, boolean value) {
    for (int i = 0; i < arr.length; i++) {
      arr[i] = value;
    }
  }

We can use the below test method (main method in this case) to test:

  // Test Method
  public static void main(String[] args) {
    int primes[] = sieveOfEratosthenes(1000);
    System.out.println("No of primes=" + primes.length);
    for (int i = 0; i < primes.length; i++) {
      System.out.print(primes[i] + " ");
    }

  }

}

Back to Top