File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Program to find all the primes upto N using Sieve Of Eratosthenes technique.
2
+ // A number is called prime if it has only two factors (1 and the number itself)
3
+ import java .util .*;
4
+ public class Sieve_Of_Eratosthenes
5
+ {
6
+ public static void main (String args [])
7
+ {
8
+ Scanner sc =new Scanner (System .in );
9
+ Sieve_Of_Eratosthenes nm =new Sieve_Of_Eratosthenes ();
10
+ int n =sc .nextInt ();
11
+ // input taken upto which primes which will be displayed
12
+ boolean k []=nm .sieve_Of_Eratosthenes (n );
13
+ // method calling where an integer value is sent and a boolean array is stored as a return value
14
+ for (int i =0 ;i <=20000000 ;i ++)
15
+ {
16
+ if (k [i ])
17
+ {
18
+ System .out .print (i +" " );
19
+ }
20
+ }
21
+ System .out .println ();
22
+ }
23
+ boolean [] sieve_Of_Eratosthenes (int n )
24
+ {
25
+ boolean b []=new boolean [n +1 ];
26
+ // boolean array is created
27
+ Arrays .fill (b ,true );
28
+ b [0 ]=false ;
29
+ b [1 ]=false ;
30
+ // 0 & 1 are marked as false because they are neither prime nor composite
31
+ for (int i =2 ;i <=Math .sqrt (n );i ++)
32
+ {
33
+ // loop is started from 2
34
+ if (b [i ])
35
+ {
36
+ for (int j =i *i ;j <=n ;j +=i )
37
+ {
38
+ // every multiple of the ith value is marked as false because they have a factor i
39
+ b [j ]=false ;
40
+ }
41
+ }
42
+ }
43
+ return b ;
44
+ // boolean array is returned
45
+ }
46
+ }
You can’t perform that action at this time.
0 commit comments