Here's a simple implementation of the Sieve of Eratosthenes algorithm for generating prime numbers up to a given upper bound in Swift:
main.swift420 chars18 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.swift159 chars3 lines
gistlibby LogSnag