Created
July 30, 2014 20:13
-
-
Save erica/c4fba79d19f0423af97b to your computer and use it in GitHub Desktop.
Explore Swift Challenge #1
This file contains 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
struct PrimeGenerator : Generator { | |
typealias Element = Int | |
private var myPrimes = [Int]() // store previous primes | |
var current : Int = 2 // first prime is 2 | |
mutating func next() -> Int? { | |
if myPrimes.count == 0 {myPrimes = [2]; return 2} | |
NextNumber: while (current++ > 0) { | |
for prime in myPrimes { | |
// If a number has a prime factor it is not prime | |
if current % prime == 0 {continue NextNumber} | |
} | |
myPrimes += current | |
break | |
} | |
return current | |
} | |
} | |
func factors(number : Int) -> [Int] { | |
var myFactors = [Int]() // Resulting factors, may contain duplicates | |
var myPrimes = PrimeGenerator() // On demand prime search | |
var remainder = number // Portion remaining to factor | |
var currentPrime = myPrimes.next()! // Pull out the first prime (2) | |
while remainder > currentPrime { | |
// Fetch all factors of the current prime | |
while remainder % currentPrime == 0 { | |
myFactors += currentPrime | |
remainder /= currentPrime | |
} | |
// Move to the next prime | |
currentPrime = myPrimes.next()! | |
} | |
// If the number is a prime itself, add it to the factor set | |
if (remainder > 1) { | |
myFactors += currentPrime | |
} | |
return myFactors | |
} | |
if (NSProcessInfo.processInfo().arguments.count < 2) | |
{ | |
println("Usage: \(NSProcessInfo.processInfo().arguments[0]) value-to-factor") | |
Darwin.exit(-1) | |
} | |
var num : Int = NSProcessInfo.processInfo().arguments[1].integerValue | |
println(factors(num)) | |
// Answer on 2011 Mac Mini: 0.012u 0.004s 0:00.01 100.0% 0+0k 0+0io 6pf+0w |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment