-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_sieve.java
More file actions
35 lines (27 loc) · 878 Bytes
/
simple_sieve.java
File metadata and controls
35 lines (27 loc) · 878 Bytes
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
// Sieve of Erathosthenes: print prime numbers up to n
//Brute force approach: check for each number from 2 to n if it is prime or not. Time complexity: O(n*sqrt(n))
// Optimised approach: Sieve of Erathosthenes: Time complexity: O(n*log(log(n)))
public class simple_sieve {
public static void simpleSieve(int n){
boolean[] prime = new boolean[n+1];
for(int i=0; i<=n; i++){
prime[i] = true;
}
for(int i=2; i*i <= n; i++){
if(prime[i] == true){
for(int j = i*i; j<= n;j+=i){
prime[j] = false;
}
}
}
for(int i=2; i<=n; i++){
if(prime[i] == true){
System.out.print(i+" ");
}
}
}
public static void main(String[] args) {
int n = 30;
simpleSieve(n);
}
}