From f35e9a7d81b027ef6efb195efdd6e511e13bc5a4 Mon Sep 17 00:00:00 2001 From: Rohan Anand <96521078+rohan472000@users.noreply.github.com> Date: Fri, 7 Apr 2023 18:20:43 +0530 Subject: [PATCH] Update SieveOfEratosthenes.java (#4149) --- .../others/SieveOfEratosthenes.java | 32 +++---------------- 1 file changed, 5 insertions(+), 27 deletions(-) diff --git a/src/main/java/com/thealgorithms/others/SieveOfEratosthenes.java b/src/main/java/com/thealgorithms/others/SieveOfEratosthenes.java index a62cbbda..3ffc3806 100644 --- a/src/main/java/com/thealgorithms/others/SieveOfEratosthenes.java +++ b/src/main/java/com/thealgorithms/others/SieveOfEratosthenes.java @@ -4,45 +4,24 @@ import java.util.Arrays; /** * Sieve of Eratosthenes is an ancient algorithm for finding all prime numbers - * up to any given limit. It does so by iteratively marking as composite (i.e., - * not prime) the multiples of each prime, starting with the first prime number, - * 2. The multiples of a given prime are generated as a sequence of numbers - * starting from that prime, with constant difference between them that is equal - * to that prime. This is the sieve's key distinction from using trial division - * to sequentially test each candidate number for divisibility by each prime. - * Once all the multiples of each discovered prime have been marked as - * composites, the remaining unmarked numbers are primes. - *

- * Poetry about Sieve of Eratosthenes: - *

- * Sift the Two's and Sift the Three's:

- *

- * The Sieve of Eratosthenes.

- *

- * When the multiples sublime,

- *

- * The numbers that remain are Prime.

+ * up to any given limit. * * @see Wiki */ public class SieveOfEratosthenes { /** - * @param n The number till which we have to check for prime Prints all the - * prime numbers till n. Should be more than 1. - * @return array of all prime numbers between 0 to n + * Finds all prime numbers till n. + * + * @param n The number till which we have to check for primes. Should be more than 1. + * @return Array of all prime numbers between 0 to n. */ public static int[] findPrimesTill(int n) { - // Create array where index is number and value is flag - is that number a prime or not. - // size of array is n + 1 cause in Java array indexes starts with 0 Type[] numbers = new Type[n + 1]; - - // Start with assumption that all numbers except 0 and 1 are primes. Arrays.fill(numbers, Type.PRIME); numbers[0] = numbers[1] = Type.NOT_PRIME; double cap = Math.sqrt(n); - // Main algorithm: mark all numbers which are multiples of some other values as not prime for (int i = 2; i <= cap; i++) { if (numbers[i] == Type.PRIME) { for (int j = 2; i * j <= n; j++) { @@ -51,7 +30,6 @@ public class SieveOfEratosthenes { } } - //Write all primes to result array int primesCount = (int) Arrays .stream(numbers) .filter(element -> element == Type.PRIME)