Last active
May 24, 2018 10:55
-
-
Save danielctull/e66e906d54b0c2766a3b42769973c5ca to your computer and use it in GitHub Desktop.
Function to find the nth prime.
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
extension Int { | |
func isDivisible(by value: Int) -> Bool { | |
return self % value == 0 | |
} | |
} | |
extension Array where Element == Int { | |
func containsDivisor(of value: Int) -> Bool { | |
return contains(where: value.isDivisible(by:)) | |
} | |
} | |
// 1-indexed | |
func prime(at index: Int) -> Int? { | |
let numbers = 2... | |
var primes: [Int] = [] | |
for number in numbers { | |
guard primes.count < index else { | |
break | |
} | |
if !primes.containsDivisor(of: number) { | |
primes.append(number) | |
} | |
} | |
return primes.last | |
} | |
print(prime(at: 100)!) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment