From 8078683c43da0e9b698d053f57c73447888a0b1b Mon Sep 17 00:00:00 2001 From: soumya1810 Date: Fri, 4 Oct 2024 12:29:43 +0530 Subject: [PATCH] Added Solution code of SieveOfEratosthenes in java --- Java/SieveOfEratosthenes.java | 60 +++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Java/SieveOfEratosthenes.java diff --git a/Java/SieveOfEratosthenes.java b/Java/SieveOfEratosthenes.java new file mode 100644 index 0000000..91f3167 --- /dev/null +++ b/Java/SieveOfEratosthenes.java @@ -0,0 +1,60 @@ +public class SieveOfEratosthenes { + //Driver Code + public static void main(String[] args) { + + Scanner input= new Scanner(System.in); + System.out.println("Enter a number : "); + int a= input.nextInt(); + System.out.println("The number of primes ="); + int primes = countPrimes(a); + System.out.println(primes); + + + + } + public static int countPrimes(int n) { + + if(n<2) return 0; + //checking for 0 & 1 + boolean[] composites = new boolean[n]; + //Array of composites --> true represents composites and false represents prime + int limit = (int)Math.sqrt(n); + for(int i=2; i<=limit;i++) { + if(composites[i]==false) { + //mark all the multiples of i as true. + //The first index to be flipped to true is i*i + for(int j= i*i; j