# Java Program to Generate Prime Numbers Using Sieve of Sundaram

This is a Java Program to Implement Sieve Of Sundaram Algorithm. This is a program to find all primes less than a number.

Here is the source code of the Java Program to Implement Sieve Of Sundaram Algorithm. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

1. /**
2.  ** Java Program to implement Sieve Of Sundaram Prime generation
3.  **/
4.
5. import java.util.Scanner;
6.
7. /** Class SieveOfSundaram **/
8. public class  SieveOfSundaram
9. {
10.     /** Function to calculate all primes less than n **/
11.     private boolean[] calcPrimes(int limit)
12.     {
13.         int n = limit/2;
14.         /** initialize the sieve **/
15.         boolean[] prime = new boolean[limit];
16.
17.         for (int i = 1; i < n; i++)
18.             for (int j = i; j <= (n - i) / (2 * i + 1); j++)
19.                 prime[i + j + 2 * i * j] = true;
20.
21.         return prime;
22.     }
23.     /** Function to get all primes **/
24.     public void getPrimes(int N)
25.     {
26.         boolean[] primes = calcPrimes(N);
27.         display(primes);
28.     }
29.     /** Function to display all primes **/
30.     public void display(boolean[] primes)
31.     {
32.         System.out.print("\nPrimes = 2 3 ");
33.         for (int i = 2; i < primes.length/2; i++)
34.             if (!primes[i])
35.                 System.out.print((2 * i + 1) +" ");
36.         System.out.println();
37.     }
38.     /** Main function **/
39.     public static void main (String[] args)
40.     {
41.         Scanner scan = new Scanner(System.in);
42.         System.out.println("Sieve Of Sundaram Prime Algorithm Test\n");
43.         /** Make an object of SieveOfSundaram class **/
44.          SieveOfSundaram sos = new  SieveOfSundaram();
45.         /** Accept n **/
46.         System.out.println("Enter number to find all primes less than the number\n");
47.         int n = scan.nextInt();
48.         sos.getPrimes(n);
49.     }
50. }

Sieve Of Sundaram Prime Algorithm Test

Enter number to find all primes less than the number

500

Primes = 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197
199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313
317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439
443 449 457 461 463 467 479 487 491 499

Sanfoundry Global Education & Learning Series – 1000 Java Programs.