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

Java 8Object Oriented ProgrammingProgramming

#### Complete Java Programming Fundamentals With Sample Projects

98 Lectures 7.5 hours

#### Get your Java dream job! Beginners interview preparation

85 Lectures 6 hours

#### Core Java bootcamp program with Hands on practice

Featured

99 Lectures 17 hours

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 = false;
isprime = 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 = false;
isprime = 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