generate prime numbers in swift

Here's a simple implementation of the Sieve of Eratosthenes algorithm for generating prime numbers up to a given upper bound in Swift:

main.swift
func sieveOfEratosthenes(_ n: Int) -> [Int] {
    var primes = [Bool](repeating: true, count: n + 1)
    primes[0] = false
    primes[1] = false
    
    for i in 2...Int(sqrt(Double(n))) {
        if primes[i] {
            var j = i * 2
            while j <= n {
                primes[j] = false
                j += i
            }
        }
    }
    
    return primes.enumerated().compactMap { $1 ? $0 : nil }
}
420 chars
18 lines

This function takes an integer n as input and returns an array of prime numbers up to n. The array is generated using a Boolean sieve that marks all composite numbers (i.e. non-prime numbers) as false, and then returns the indices of the remaining true values, which correspond to prime numbers.

The implementation also includes a simple optimization that skips all even numbers after the number 2, since they are not prime.

To use this function, simply call it with an upper bound value of your choice, like so:

main.swift
let primes = sieveOfEratosthenes(100)
print(primes) // prints [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
159 chars
3 lines

gistlibby LogSnag