Java Program to get prime numbers using the Sieve of Eratosthenes algorithm

Java 8Object Oriented ProgrammingProgramming

To find all prime numbers up to any given limit, use the Sieve of Eratosthenes algorithm. At first we have set the value to be checked −

int val = 30;

Now, we have taken a boolean array with a length one more than the val −

boolean[] isprime = new boolean[val + 1];

Loop through val and set numbers as TRUE. Also, set 0 and 1 as false since both these number are not prime −

isprime[0] = false;
isprime[1] = false;

Following is an example showing rest of the steps to get prime numbers using the Sieve of Eratosthenes algorithm −

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      // set a value to check
      int val = 30;
      boolean[] isprime = new boolean[val + 1];
      for (int i = 0; i <= val; i++)
      isprime[i] = true;
      // 0 and 1 is not prime
      isprime[0] = false;
      isprime[1] = false;
      int n = (int) Math.ceil(Math.sqrt(val));
      for (int i = 0; i <= n; i++) {
         if (isprime[i])
         for (int j = 2 * i; j <= val; j = j + i)
         // not prime
         isprime[j] = false;
      }
      int myPrime;
      for (myPrime = val; !isprime[myPrime]; myPrime--) ; // empty loop body
      System.out.println("Largest prime less than or equal to " + val + " = " + myPrime);
   }
}

Output

Largest prime less than or equal to 30 = 29
raja
Published on 23-Apr-2019 08:41:23
Advertisements