Skip to content

Instantly share code, notes, and snippets.

@hollance
Last active August 29, 2015 14:05
Show Gist options
  • Select an option

  • Save hollance/e76cb2c7ff2e2daa3492 to your computer and use it in GitHub Desktop.

Select an option

Save hollance/e76cb2c7ff2e2daa3492 to your computer and use it in GitHub Desktop.
Solution to Explore Swift Challenge #1
/*
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