I just finished Project Euler #16 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.
2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2^1000?
import Foundation
func addMulToResult(inout results:[Int], var mulResult:Int, index:Int) {
if index == results.count {
results.append(0)
}
mulResult = results[index] + mulResult
var result = mulResult % 10
results[index] = result
var retain = mulResult / 10
if retain > 0 {
addMulToResult(&results, retain, index + 1)
}
}
func infMult(left:[Int], right:[Int]) -> [Int] {
var results:[Int] = [Int]()
for (j, rightNumber) in enumerate(reverse(right)) {
for (i, leftNumber) in enumerate(reverse(left)) {
let mulResult = leftNumber * rightNumber
addMulToResult(&results, mulResult, i + j)
}
}
return results.reverse()
}
func infPow(x:Int, var power:Int) -> [Int] {
var result = [1]
var xArray = intToIntArray(x)
while power > 0 {
result = infMult(result, xArray)
power--
}
return result
}
func intToIntArray(var number:Int) -> [Int] {
var intArray:[Int] = []
while number > 0 {
intArray.append(number % 10)
number /= 10
}
return intArray.reverse()
}
func powerDigitSum(x:Int, var power:Int) -> Int {
let powerSum = infPow(x, power)
let result = reduce(powerSum, 0) { $0 + $1 }
return result
}
func euler16() {
let number = powerDigitSum(2, 1000)
println(number)
}
func printTimeElapsedWhenRunningCode(operation:() -> ()) {
let startTime = CFAbsoluteTimeGetCurrent()
operation()
let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
println("Time elapsed : \(timeElapsed) s")
}
printTimeElapsedWhenRunningCode(euler16)
The code executes in 0.06s