Skip to content

Instantly share code, notes, and snippets.

@superlopuh
Created September 8, 2014 08:21
Show Gist options
  • Save superlopuh/f1247f5316670a009ef6 to your computer and use it in GitHub Desktop.
Save superlopuh/f1247f5316670a009ef6 to your computer and use it in GitHub Desktop.
#!/usr/bin/env xcrun swift
import Cocoa
func smallestPrimeFactorOf(integer: Int) -> Int? {
let upperBound = Int(sqrt(Double(integer)))
var attempt = 2
while attempt <= upperBound {
if integer % attempt == 0 {
return attempt
}
attempt++
}
return nil
}
func largestPrimeFactor(integer: Int) -> Int? {
var largestPrimeFactor: Int?
var smallestPrimeFactor = smallestPrimeFactorOf(integer)
var attempt = integer
while (smallestPrimeFactor != nil) {
attempt /= smallestPrimeFactor!
smallestPrimeFactor = smallestPrimeFactorOf(attempt)
}
return attempt
}
println(largestPrimeFactor(600851475143))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment