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
+ import java .io .BufferedReader ;
2
+ import java .io .IOException ;
3
+ import java .io .InputStreamReader ;
4
+ import java .util .ArrayList ;
5
+ import java .util .Arrays ;
6
+
7
+ public class PrimeSieve {
8
+
9
+ /*
10
+ For a given N, it will print all primes less than or equal to N
11
+ */
12
+ public static void main (String [] args ) throws IOException {
13
+ System .out .println ("Enter the N" );
14
+
15
+ BufferedReader br = new BufferedReader (new InputStreamReader (System .in ));
16
+
17
+ int N = Integer .parseInt (br .readLine ());
18
+
19
+ Boolean [] visited = new Boolean [N + 1 ];
20
+ Arrays .fill (visited , Boolean .FALSE );
21
+
22
+ ArrayList <Integer > primes = new ArrayList <>();
23
+
24
+ primes .add (2 );
25
+
26
+ for (int i = 3 ; i * i <= N ; i += 2 ) {
27
+ if (!visited [i ]) {
28
+ for (int j = i * i ; j <= N ; j += 2 * i ) {
29
+ visited [j ] = true ;
30
+ }
31
+ }
32
+ }
33
+
34
+ for (int i = 3 ; i <= N ; i += 2 ) {
35
+ if (!visited [i ])
36
+ primes .add (i );
37
+ }
38
+
39
+ System .out .println ("Primes <= N are:" );
40
+
41
+ primes .forEach (System .out ::println );
42
+
43
+ br .close ();
44
+ }
45
+
46
+ }
You can’t perform that action at this time.
0 commit comments