Task definition: Given a integer number n, calculate all primes smaller than or equal to n (It may be including or not including).
For example if we will not include upper bound, if n is 23, following prime numbers should be:
2, 3, 5, 7, 11, 13, 17, 19
Algorithm is following (for case when not including upper bound):
GitHub source code: Eratosthenes Sieve in Swift
For example if we will not include upper bound, if n is 23, following prime numbers should be:
2, 3, 5, 7, 11, 13, 17, 19
Algorithm is following (for case when not including upper bound):
- Make an boolean array of size equals n, all values fill with true
- Assign elements at 0 and 1 indexes to false, because 0 and 1 is NOT prime numbers by default
- Since index 2 until last index of array if item at this index if true then make inner for loop.
- Inner for loop should be for each multiples of current number. Values at these multiples indexes must be assigned to false
- Finally converts our array of boolean values to array of integer values. After all iterations of sieve we will have true values at indexes which are prime numbers. So if value of array item is true then its index is prime number.
GitHub source code: Eratosthenes Sieve in Swift