-
Notifications
You must be signed in to change notification settings - Fork 367
Expand file tree
/
Copy pathSieve_erastonetihis.java
More file actions
32 lines (30 loc) · 942 Bytes
/
Sieve_erastonetihis.java
File metadata and controls
32 lines (30 loc) · 942 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
import java.util.Scanner;
public class Sieve_erastonetihis {
public static void main(String[] args) {
// If you have to find prime numbers till n
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
//creating boolean array to mark multiples of primes as true
//So all true element will be prime numbers
if(n<=1){
System.out.println("There is no prime numbers");
}
boolean [] primes = new boolean[n+1];
sieve(n, primes);
}
public static void sieve(int n, boolean [] primes){
for(int i=2;i*i<=n;i++){
if(!primes[i]){
for(int j=2*i;j<=n;j+=i){
primes[j]= true;
}
}
}
for(int i=2;i<=n;i++){
if(!primes[i]){
System.out.print(i + " ");
}
}
}
}