forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SieveOfEratosthenes.java
63 lines (45 loc) · 1.4 KB
/
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/* Sieve of Eratosthenes :
Sieve of Eratosthenes is an ancient algorithm for finding all prime numbers up to any given limit.
It does so by iteratively marking as composite (i.e., not prime) the multiples of each prime, starting with
the first prime number, 2. The multiples of a given prime are generated as a sequence of numbers starting from that prime,
with constant difference between them that is equal to that prime.
*/
import java.util.Scanner;
public class SieveOfEratosthenes {
public static void sieve(int n) {
boolean prime[]=new boolean[n+1];
for(int i=0;i<=n;i++) {
prime[i]=true;
}
prime[0]=prime[1]=false;
for(int i=2;i*i<=n;i++) {
// If a number is prime :
if(prime[i]==true) {
// Marking all multiples of that number as false
for(int j=i*i;j<=n;j+=i) {
prime[j]=false;
}
}
}
// Printing all prime number less than n :
for(int i=0;i<=n;i++) {
if(prime[i]==true) {
System.out.print(i+" ");
}
}
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("Enter a number : ");
int n=sc.nextInt();
System.out.println("Prime number less than or equal to "+n+" are : ");
sieve(n);
}
/*
Sample Input :
Enter a number : 100
Sample Output :
Prime number less than or equal to 100 are :
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
*/
}