Site icon

Prime number generator in java using Sieve of Eratosthenes algorithm

Algorithm – find prime numbers till given number ( 2 to number)

Example: Prime numbers using Sieve of Eratosthenes algorithm

Fig1 : Generate prime numbers till 30
Fig 2: Eliminates number multiple of 2
Fig 3: Eliminates all numbers multiple of 3
Fig 4: Eliminates all numbers multiple of 5

The unmarked numbers in the table are prime numbers till 30: 2 3 5 7 11 13 17 19 23 29

Program: prime number generator in java using Sieve of Eratosthenes algorithm

package org.learn.arrays;

import java.util.Arrays;
import java.util.Scanner;

public class SieveEratosthenes {
	public static void generatePrimeNumbers(int maxNumber) {

		boolean[] isPrime = new boolean[maxNumber + 1];
		Arrays.fill(isPrime, true);

		int primeRange = (int) Math.sqrt(maxNumber);
		for (int number = 2; number <= primeRange; number++) {
			if (isPrime[number]) {
				for (int iEliminate = number * number; iEliminate <= maxNumber; iEliminate += number) {
					isPrime[iEliminate] = false;
				}
			}
		}
		int number = 2;
		while (number <= maxNumber) {
			if (isPrime[number]) {
				System.out.printf("%d ", number);
			}
			number++;
		}

		return;
	}

	public static void main(String[] args) {

		try (Scanner scanner = new Scanner(System.in)) {
			System.out.print("1. Enter the number:  ");
			int maxNumber = scanner.nextInt();
			System.out.printf("2. Prime numbers till %d : ", maxNumber);
			generatePrimeNumbers(maxNumber);
		}
	}
}

Output: prime numbers in java using Sieve of Eratosthenes algorithm

1. Enter the number:  30
2. Prime numbers till 30 : 2 3 5 7 11 13 17 19 23 29 

1. Enter the number:  50
2. Prime numbers till 50 : 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 
Exit mobile version