diff --git a/Mathematics/sieve of Eratosthenes/Swift/sieve-of-eratosthenes.swift b/Mathematics/sieve of Eratosthenes/Swift/sieve-of-eratosthenes.swift new file mode 100644 index 000000000..b451b0ce6 --- /dev/null +++ b/Mathematics/sieve of Eratosthenes/Swift/sieve-of-eratosthenes.swift @@ -0,0 +1,26 @@ +func sieve(_ n: Int) -> [Bool] { + var i = 2 + var primes = Array(repeating: true, count: n) + + while i < n { + if primes[i] == true { + var j = i*i + while j < n { + primes[j] = false + j += i + } + } + i += 1 + } + + return primes +} + +// Usage +let x = sieve(10) +// Prints all prime numbers till 10 +for (i,prime) in x.enumerated() { + if prime { + print(i) + } +}