Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Created May 10, 2016 04:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JadenGeller/f998071fe71c2bc2976ef6465f0e6e5d to your computer and use it in GitHub Desktop.
Save JadenGeller/f998071fe71c2bc2976ef6465f0e6e5d to your computer and use it in GitHub Desktop.
Swift Lazy Prime Factorization
import Darwin
extension Int {
// Lazily computes prime factors
public var primeFactors: AnySequence<Int> {
func factor(input: Int) -> (prime: Int, remainder: Int) {
let end = Int(sqrt(Float(input)))
if end > 2 {
for prime in 2...end {
if input % prime == 0 {
return (prime, input / prime)
}
}
}
return (input, 1)
}
var current = self
return AnySequence(anyGenerator {
guard current != 1 else { return nil }
let result = factor(current)
current = result.remainder
return result.prime
})
}
}
print(Array(18.primeFactors))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment