Java Program for Sieve of Eratosthenes
Last Updated :
05 May, 2021
Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number.
For example, if n is 10, the output should be “2, 3, 5, 7”. If n is 20, the output should be “2, 3, 5, 7, 11, 13, 17, 19”.
Java
class SieveOfEratosthenes
{
void sieveOfEratosthenes( int n)
{
boolean prime[] = new boolean [n+ 1 ];
for ( int i= 0 ;i<=n;i++)
prime[i] = true ;
for ( int p = 2 ; p*p <=n; p++)
{
if (prime[p] == true )
{
for ( int i = p*p; i <= n; i += p)
prime[i] = false ;
}
}
for ( int i = 2 ; i <= n; i++)
{
if (prime[i] == true )
System.out.print(i + " " );
}
}
public static void main(String args[])
{
int n = 30 ;
System.out.print( "Following are the prime numbers " );
System.out.println( "smaller than or equal to " + n);
SieveOfEratosthenes g = new SieveOfEratosthenes();
g.sieveOfEratosthenes(n);
}
}
|
Output
Following are the prime numbers smaller than or equal to 29
2 3 5 7 11 13 17 19 23 29
Please refer complete article on Sieve of Eratosthenes for more details!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...