Skip to content

Instantly share code, notes, and snippets.

@prasadpamidi
Last active November 5, 2015 19:12
Show Gist options
  • Save prasadpamidi/4e7e2a0c752594f89bfe to your computer and use it in GitHub Desktop.
Save prasadpamidi/4e7e2a0c752594f89bfe to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes Algorithm implementation in Swift
//Algorithm: Sieve of Eratosthenes
//Swift 2.0 implementation for retreving all the primes until the given limit
func findPrimesUntil(limit limit: Int) -> [Int]? {
guard limit > 1 else {
return .None
}
var primes = [Bool](count: limit+1, repeatedValue: true)
for i in 0..<2 {
primes[i] = false
}
for j in 2..<primes.count where primes[j] {
for var k = 2; k*j < primes.count; k++ {
primes[k*j] = false
}
}
return primes.enumerate().flatMap { (index: Int, element: Bool) -> Int? in
if element {
return index
}
return .None
}
}
//Sample calls
findPrimesUntil(limit: -3) //nil
findPrimesUntil(limit: Int.min) //nil
findPrimesUntil(limit: 23) //[2, 3, 5, 7, 11, 13, 17, 19, 23]
findPrimesUntil(limit: 6) //[2, 3, 5]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment