-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathSieveOfEratosthenes.java
More file actions
36 lines (29 loc) · 895 Bytes
/
SieveOfEratosthenes.java
File metadata and controls
36 lines (29 loc) · 895 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
36
mport java.util.Scanner;
import java.lang.*;
public class SieveOfEratosthenes {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number upto which you need prime numbers");
int n = scanner.nextInt();
System.out.println("Prime numbers upto " + n + " are ");
SievePrime(n);
}
private static void SievePrime(int n) {
Boolean[] arr = new Boolean[n + 1];
for (int i = 0; i < n; i++) {
arr[i] = true;
}
for (int p = 2; p * p < n; p++) {
if (arr[p]) {
for (int i = p * p; i <= n; i += p) {
arr[i] = false;
}
}
}
for (int i = 2; i <= n; i++) {
if (arr[i]) {
System.out.print(i + " ");
}
}
}
}