give me a function to generate primes in swift

Here's a function in Swift to generate prime numbers:

main.swift
func generatePrimes(upTo n: Int) -> [Int] {
    var primes = [Int]()
    var isPrime = [Bool](repeating: true, count: n+1)

    isPrime[0] = false
    isPrime[1] = false

    for i in 2...n {
        if isPrime[i] {
            primes.append(i)

            var multiple = 2
            while (i * multiple) <= n {
                isPrime[i * multiple] = false
                multiple += 1
            }
        }
    }

    return primes
}

let primes = generatePrimes(upTo: 100)
print(primes)
496 chars
25 lines

This function generatePrimes takes an integer n as input and returns an array of prime numbers up to n. It uses the Sieve of Eratosthenes algorithm to efficiently find the prime numbers.

In the main program, we call the generatePrimes function with an example value of 100 and print the resulting array of prime numbers.

The output will be: [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], which are all the prime numbers up to 100.

related categories

gistlibby LogSnag