Skip to content

Instantly share code, notes, and snippets.

@hlprmnky
Created August 5, 2015 21:42
Show Gist options
  • Select an option

  • Save hlprmnky/306f2d2d79ff478c4098 to your computer and use it in GitHub Desktop.

Select an option

Save hlprmnky/306f2d2d79ff478c4098 to your computer and use it in GitHub Desktop.
// Produce all primes from 2 to target using
// the Sieve of Eratosthenes - https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
func eratosthenes(target: Int) -> [Int] {
if target < 2 {
return []
}
var marked = Set<Int>()
return (2...target).filter {
(let number) -> Bool in
var product = number * 2
while product <= target {
if !marked.contains(product) {
marked.insert(product)
}
product += number
}
return !marked.contains(number)
}
}
// If the list of primes for target contains target, it's prime
func isPrime(target: Int) -> Bool {
return eratosthenes(target).contains(target)
}
isPrime(171) // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment