Last active
August 29, 2015 14:05
-
-
Save hollance/e76cb2c7ff2e2daa3492 to your computer and use it in GitHub Desktop.
Solution to Explore Swift Challenge #1
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
| /* | |
| The code from https://gist.github.com/GarthSnyder/c8efe80675cd00322b51 | |
| rewritten as a Swift sequence and generator. | |
| */ | |
| import Foundation | |
| struct PrimeFactorGenerator: GeneratorType { | |
| var n: Int | |
| var divisor = 2 | |
| init(_ number: Int) { | |
| n = number | |
| } | |
| mutating func next() -> Int? { | |
| for ; divisor <= n; ++divisor { | |
| if n % divisor == 0 { | |
| n /= divisor | |
| return divisor | |
| } | |
| } | |
| return nil | |
| } | |
| } | |
| struct PrimeFactorSequence: SequenceType { | |
| var n: Int | |
| init(_ number: Int) { | |
| n = number | |
| } | |
| typealias Generator = PrimeFactorGenerator | |
| func generate() -> Generator { | |
| return PrimeFactorGenerator(n) | |
| } | |
| } | |
| for i in PrimeFactorSequence(600851475143) { | |
| println(i) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment