Last active
August 29, 2015 14:06
-
-
Save superlopuh/9d11af4ae1b578623fcd to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env xcrun swift | |
import Cocoa | |
func smallestPrimeFactorOf(integer: Int, andMinGuess minGuess: Int = 2) -> Int? { | |
let upperBound = Int(sqrt(Double(integer))) | |
var attempt = minGuess | |
while attempt <= upperBound { | |
if integer % attempt == 0 { | |
return attempt | |
} | |
attempt++ | |
} | |
return nil | |
} | |
func largestPrimeFactorOf(var integer: Int) -> Int? { | |
var largestPrimeFactor: Int? | |
var smallestPrimeFactor = smallestPrimeFactorOf(integer) | |
if smallestPrimeFactor == nil { | |
return nil | |
} | |
var attempt = integer | |
while (smallestPrimeFactor != nil) { | |
attempt /= smallestPrimeFactor! | |
smallestPrimeFactor = smallestPrimeFactorOf(attempt, withMinGuess: smallestPrimeFactor!) | |
} | |
return attempt | |
} | |
print(largestPrimeFactorOf(600851475143)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment