Search This Blog

Saturday, October 20, 2018

Eratosthenes Sieve in Swift

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):


  1. Make an boolean array of size equals n, all values fill with true
  2. Assign elements at 0 and 1 indexes to false, because 0 and 1 is NOT prime numbers by default
  3. Since index 2 until last index of array if item at this index if true then make inner for loop. 
    1. Inner for loop should be for each multiples of current number. Values at these multiples indexes must be assigned to false
  4. 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.


// Not including max number
func sieveNotIncluding(max: Int) -> [Int] {
    guard max > 1 else { return [] }
    
    var sieve = [Bool](repeating: true, count: max)
    
    sieve[0] = false
    sieve[1] = false
    
    for i in 2..<max where sieve[i] == true {
        for j in stride(from: i*i, to: max, by: i) {
            sieve[j] = false
        }
    }
    
    return sieve.enumerated().compactMap { $1 == true ? $0 : nil }
}

sieveNotIncluding(max: 23) // [2, 3, 5, 7, 11, 13, 17, 19]


// Including max number
func sieveIncluding(max: Int) -> [Int] {
    guard max > 1 else { return [] }
    
    var sieve = [Bool](repeating: true, count: max + 1)
    
    sieve[0] = false
    sieve[1] = false
    
    for i in 2...max where sieve[i] == true {
        for j in stride(from: i*i, through: max, by: i) {
            sieve[j] = false
        }
    }
    
    return sieve.enumerated().compactMap { $1 == true ? $0 : nil }
}

sieveIncluding(max: 23) // [2, 3, 5, 7, 11, 13, 17, 19, 23]

GitHub source code: Eratosthenes Sieve in Swift