Created
May 10, 2016 04:17
-
-
Save JadenGeller/f998071fe71c2bc2976ef6465f0e6e5d to your computer and use it in GitHub Desktop.
Swift Lazy Prime Factorization
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
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