From 684964c6de4a6048d5a5ca095ccddb27eb348a01 Mon Sep 17 00:00:00 2001 From: BhargavReddyg <65347488+BhargavReddyg@users.noreply.github.com> Date: Mon, 5 Oct 2020 14:15:03 +0530 Subject: [PATCH] Added the Sieve of Eratosthenes Program --- Sieve of Eratosthenes | 51 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Sieve of Eratosthenes diff --git a/Sieve of Eratosthenes b/Sieve of Eratosthenes new file mode 100644 index 0000000..f2ef21e --- /dev/null +++ b/Sieve of Eratosthenes @@ -0,0 +1,51 @@ +// { Driver Code Starts +//Initial Template for Java +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 primes = ob.sieveOfEratosthenes(N); + for(int prime : primes) { + System.out.print(prime+" "); + } + System.out.println(); + } + } +} +// } Driver Code Ends + + +//User function Template for Java +class Solution{ + static ArrayList sieveOfEratosthenes(int N){ + // code here + ArrayList numbers=new ArrayList(); + 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; + } +}