From 701d5d1855d9e371e718ea7442f34b688332e7c9 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Thu, 28 Sep 2017 11:38:20 -0700 Subject: [PATCH] Added SieveOfEratosthenes.java --- Others/SieveOfEratosthenes.java | 49 +++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Others/SieveOfEratosthenes.java diff --git a/Others/SieveOfEratosthenes.java b/Others/SieveOfEratosthenes.java new file mode 100644 index 00000000..4b6fd5b7 --- /dev/null +++ b/Others/SieveOfEratosthenes.java @@ -0,0 +1,49 @@ +/** + * + * @author Varun Upadhyay (https://github.com/varunu28) + * + */ +public class SieveOfEratosthenes { + + /** + * This method implements the Sieve of Eratosthenes Algorithm + * + * @param n The number till which we have to check for prime + * Prints all the prime numbers till n + **/ + + public static void findPrimesTillN(int n) { + int[] arr = new int[n+1]; + + for (int i=0;i<=n;i++) { + arr[i] = 1; + } + + arr[0] = arr[1] = 0; + + for (int i=2;i<=Math.sqrt(n);i++) { + if (arr[i] == 1) { + for (int j=2;i*j <= n;j++) { + arr[i*j] = 0; + } + } + } + + for (int i=0;i