Created
August 5, 2015 21:42
-
-
Save hlprmnky/306f2d2d79ff478c4098 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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