Skip to content

Instantly share code, notes, and snippets.

@danielctull
Last active May 24, 2018 10:55
Show Gist options
  • Save danielctull/e66e906d54b0c2766a3b42769973c5ca to your computer and use it in GitHub Desktop.
Save danielctull/e66e906d54b0c2766a3b42769973c5ca to your computer and use it in GitHub Desktop.
Function to find the nth prime.
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