forked from BhargavReddyg/HackOctober-Java-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSieve of Eratosthenes.java
More file actions
50 lines (40 loc) · 1.06 KB
/
Sieve of Eratosthenes.java
File metadata and controls
50 lines (40 loc) · 1.06 KB
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
import java.io.*;
import java.util.*;
class GFG
{
public static void main(String args[])throws IOException
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0)
{
int N=sc.nextInt();
Solution ob = new Solution();
ArrayList<Integer> primes = ob.sieveOfEratosthenes(N);
for(int prime : primes) {
System.out.print(prime+" ");
}
System.out.println();
}
}
}
class Solution{
static ArrayList<Integer> sieveOfEratosthenes(int N){
// code here
ArrayList<Integer> numbers=new ArrayList<Integer>();
int i=0;
boolean isPrime[]=new boolean[N+1];
Arrays.fill(isPrime,true);
for(i=2;i*i<=N;i++){
if(isPrime[i]){
for(int j=2*i;j<=N;j=j+i)
isPrime[j]=false;
}
}
for(i=2;i<=N;i++){
if(isPrime[i])
numbers.add(i);
}
return numbers;
}
}