forked from iiitv/algos
-
Notifications
You must be signed in to change notification settings - Fork 2
/
SieveOfEratosthenes.java
35 lines (32 loc) · 995 Bytes
/
SieveOfEratosthenes.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/*
* Following implementation of sieve of eratosthenes returns a boolean array which contains true is its index is prime
* less than or equal to a number n.
* Space complexity : O(n).
* Time complexity : O(n).
*/
public class SieveOfEratosthenes {
public static boolean[] sieveOfEratosthenes(int n) {
int sqrtOfn = (int)Math.sqrt(n) + 1;
boolean[] primes = new boolean[n + 1];
for (int i = 2; i < n + 1; ++i) {
primes[i] = true;
}
for (int i = 2; i <= sqrtOfn; ++i) {
if (primes[i]) {
for (int j = 2 * i; j < n + 1; j += i) {
primes[j] = false;
}
}
}
return primes;
}
public static void main(String[] args) {
int n = 100;
boolean[] primes = sieveOfEratosthenes(n);
for (int i = 2; i < n + 1; ++i) {
if (primes[i]) {
System.out.print(i + " ");
}
}
}
}