
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get Prime Numbers Using the Sieve of Eratosthenes Algorithm in Java
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
Advertisements