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