Skip to content

Commit a17475d

Browse files
committed
Sieve of eratosthenes
1 parent e61eedc commit a17475d

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Programs/Sieve_Of_Eratosthenes.java

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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+
}

0 commit comments

Comments
 (0)