Skip to content

Commit a45d4d4

Browse files
author
codehouseindia
authored
Merge pull request codehouseindia#108 from BhargavReddyg/patch-1
Added the Sieve of Eratosthenes Program
2 parents 069f47e + 684964c commit a45d4d4

1 file changed

Lines changed: 51 additions & 0 deletions

File tree

Sieve of Eratosthenes

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// { Driver Code Starts
2+
//Initial Template for Java
3+
import java.io.*;
4+
import java.util.*;
5+
6+
class GFG
7+
{
8+
public static void main(String args[])throws IOException
9+
{
10+
Scanner sc = new Scanner(System.in);
11+
int t = sc.nextInt();
12+
while(t-- > 0)
13+
{
14+
int N=sc.nextInt();
15+
16+
Solution ob = new Solution();
17+
ArrayList<Integer> primes = ob.sieveOfEratosthenes(N);
18+
for(int prime : primes) {
19+
System.out.print(prime+" ");
20+
}
21+
System.out.println();
22+
}
23+
}
24+
}
25+
// } Driver Code Ends
26+
27+
28+
//User function Template for Java
29+
class Solution{
30+
static ArrayList<Integer> sieveOfEratosthenes(int N){
31+
// code here
32+
ArrayList<Integer> numbers=new ArrayList<Integer>();
33+
int i=0;
34+
35+
36+
boolean isPrime[]=new boolean[N+1];
37+
Arrays.fill(isPrime,true);
38+
39+
for(i=2;i*i<=N;i++){
40+
if(isPrime[i]){
41+
for(int j=2*i;j<=N;j=j+i)
42+
isPrime[j]=false;
43+
}
44+
}
45+
for(i=2;i<=N;i++){
46+
if(isPrime[i])
47+
numbers.add(i);
48+
}
49+
return numbers;
50+
}
51+
}

0 commit comments

Comments
 (0)