Skip to content

Commit 01f0361

Browse files
Merge pull request #102 from varunu28/master
Added SieveOfEratosthenes.java
2 parents 8b29c6c + 701d5d1 commit 01f0361

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

Others/SieveOfEratosthenes.java

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
*
3+
* @author Varun Upadhyay (https://github.com/varunu28)
4+
*
5+
*/
6+
public class SieveOfEratosthenes {
7+
8+
/**
9+
* This method implements the Sieve of Eratosthenes Algorithm
10+
*
11+
* @param n The number till which we have to check for prime
12+
* Prints all the prime numbers till n
13+
**/
14+
15+
public static void findPrimesTillN(int n) {
16+
int[] arr = new int[n+1];
17+
18+
for (int i=0;i<=n;i++) {
19+
arr[i] = 1;
20+
}
21+
22+
arr[0] = arr[1] = 0;
23+
24+
for (int i=2;i<=Math.sqrt(n);i++) {
25+
if (arr[i] == 1) {
26+
for (int j=2;i*j <= n;j++) {
27+
arr[i*j] = 0;
28+
}
29+
}
30+
}
31+
32+
for (int i=0;i<n+1;i++) {
33+
if (arr[i] == 1) {
34+
System.out.print(i + " ");
35+
}
36+
}
37+
38+
System.out.println();
39+
}
40+
41+
// Driver Program
42+
public static void main(String[] args) {
43+
int n = 100;
44+
45+
// Prints 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
46+
findPrimesTillN(n);
47+
}
48+
49+
}

0 commit comments

Comments
 (0)