Skip to content

Instantly share code, notes, and snippets.

@superlopuh
Last active August 29, 2015 14:06
Show Gist options
  • Save superlopuh/9d11af4ae1b578623fcd to your computer and use it in GitHub Desktop.
Save superlopuh/9d11af4ae1b578623fcd to your computer and use it in GitHub Desktop.
#!/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