I just finished Project Euler #12 in Swift, and since there is not any version yet on Code Review, I would like to have some comments on what I did to try to improve it.
The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have over five hundred divisors?
import Foundation
let OverNumberOfDivisors = 500
extension Int {
func isMultipleOf(factor: Int) -> Bool {
return self % factor == 0
}
}
func findPrimesFactorFrom(let smallest: Int, let toFactor: Int, inout primesFactor:[Int:Int]) {
var maxFactor = Int(sqrt(Double(toFactor)))
maxFactor = maxFactor < smallest ? smallest : maxFactor
for factor in smallest...maxFactor {
if toFactor.isMultipleOf(factor) {
primesFactor[factor] = (primesFactor[factor] ?? 0) + 1
return findPrimesFactorFrom(factor, toFactor / factor, &primesFactor)
}
}
primesFactor[toFactor] = (primesFactor[toFactor] ?? 0) + 1
}
func highlyDivisibleTriangularNumber() -> Int {
var currentNumberOfDivisors = 1
var triangleNumber = 1
var number = 1
var primesFactor:[Int:Int] = [:]
while OverNumberOfDivisors >= currentNumberOfDivisors {
number++
triangleNumber += number
primesFactor = [:]
findPrimesFactorFrom(2, triangleNumber, &primesFactor)
currentNumberOfDivisors = 1
for (index, factor) in primesFactor {
if index != 1 {
currentNumberOfDivisors *= (factor + 1)
}
}
}
return triangleNumber
}
func euler12() {
let number = highlyDivisibleTriangularNumber()
println(number)
}
func printTimeElapsedWhenRunningCode(operation:() -> ()) {
let startTime = CFAbsoluteTimeGetCurrent()
operation()
let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
println("Time elapsed : \(timeElapsed) s")
}
printTimeElapsedWhenRunningCode(euler12)
The code executes in 0.3s