Prime numbers using sieve of Eratosthenes algorithm (Java)

This program is about printing the prime numbers from 2 till the given parameter.
the algorithm that is used here is called "sieve of Eratosthenes". If you do not know it, please click here to read about it on wikipedia.

We will divide this program into three functions:

  1. Implement the static int[ ] createAndfillArray(int n) method. This method should create an array, fill it ascendingly from 2 till the given parameter and then return this array. In other words, the array should contain all the numbers in this interval [2, n].
    E.g.  createAndfillArray(10) //=>  [2, 3, 4, 5, 6, 7, 8, 9, 10]
  2. Implement the static void filterArray(int[ ] arr, int index) method. This method should filter the array by changing all multiples of the element at the given index to the value of -1.
    All the number that would have the value of -1 are non-prime numbers.
    E.g. int[] arr = createAndfillArray(10)
           filterArray(arr, 0) //=>  [2, 3, -1, 5, -1, 7, -1, 9, -1]
  3. Implement the static void printPrimeNumbersTill(int n) method. This method should print all the prime number till the given parameter by using sieve of Eratosthenes algorithm.
    E.g. printPrimeNumbersTill(20) //=>  [2, 3, 5, 7, 11, 13, 17, 19]
📢Recommended: Please try to solve the question/implement the program on your own first, before looking at the code down below.


🎁Code:

/**
 * printing the prime numbers from 2 till the given parameter.
 * @author Khaled Badran 
 * @since 28 August 2020
 */
class PrimeNumbers {


    /**
     * creates an array filled ascendingly from 2 till the given number
     * @param n the given number
     * @return the created and filled array 
     */
    static int[] createAndfillArray(int n) {

        n -= 1//because the array we create starts from the value of 2 and not from 1.
        int[] arr = new int[n];

        for(int i = 0, fillWith = 2; i < n; i++, fillWith++)
            arr[i] = fillWith;
        
        return arr;
    }


    /**
     * filters the array by changing all multiples of the element at the given index to the value of -1.
     * @param arr the array to be filtered 
     * @param index  the index of which all multiples of its element should be -1
     */
    static void filterArray(int[] arrint index) {
        
        if (arr[index== -1return

        for(int i = index; i < arr.length; i += arr[index]) 
            if(arr[i] != -1 && i != index// remove the non-prime number by changing its value to -1
                arr[i] = -1;

    } 
    

    /**
     * prints all prime numbers from 2 till the given number
     * @param n the given number
     */
    static void printPrimeNumbersTill(int n) { 

        int[] arr = createAndfillArray(n);
        
        for(int i = 0; i < arr.length / 2 ; i++)
            filterArray(arr, i);
        
        System.out.print("The prime numbers till "+ n+ " are: ");
        String s = "[";
        for(int i = 0; i < arr.length; i++)
            if(arr[i] != -1
                s += String.valueOf(arr[i] + ", ");
                    
        // now it looks like this [2, 3, 5, ...., ] 
        // we don't need to print ", " after last number 
        s += "\b\b"// "\b" is backspace, so we have deleted the last comma and space after last number
        s += "]";
        System.out.println(s);
    }

    
    public static void main(String[] args) {

        printPrimeNumbersTill(20);
        printPrimeNumbersTill(50);
        printPrimeNumbersTill(100);
    }

}

Output:


The prime numbers till 20 are: [235711131719]
The prime numbers till 50 are: [23571113171923293137414347]
The prime numbers till 100 are: [23571113171923293137414347,                                  53596167717379838997]



Comments