- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to get prime numbers using the Sieve of Eratosthenes algorithm
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
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
- Related Articles
- C++ Program to Implement Sieve of eratosthenes to Generate Prime Numbers Between Given Range
- Sieve of Eratosthenes in java
- Python Program for Sieve of Eratosthenes
- Using Sieve of Eratosthenes to find primes JavaScript
- C++ Program to Generate Prime Numbers Between a Given Range Using the Sieve of Sundaram
- Java Program to get the prime numbers with BigInteger type
- C++ Program to Implement Sieve of Atkin to Generate Prime Numbers Between Given Range
- C++ Program to Implement Wheel Sieve to Generate Prime Numbers Between Given Range
- C++ Program to Implement Segmented Sieve to Generate Prime Numbers Between Given Range
- Which is the fastest algorithm to find prime numbers using C++?
- Java Program to Display Prime Numbers Between Intervals Using Function
- Java Program to Find G.C.D and L.C.M of Two Numbers Using Euclid\'s Algorithm
- Java program to print prime numbers below 100
- Java Program to Display Prime Numbers Between Two Intervals
- C++ Program to Find GCD of Two Numbers Using Recursive Euclid Algorithm

Advertisements