func digitSum(var x : Int) -> Int {
var result = 0
while x > 0 {
result += x % 10
x /= 10
}
return result
}
func powerDigitSum(x:Int, power:Int) -> Int {
let powerSum = infPow(x, power)
let result = reduce(powerSum, 0) { $0 + digitSum($1) }
return result
}
Remark: I would have expected a greatsome performance improvement by using a better
exponentiation algorithm in infPow()
, such as Exponentiation by squaring (see also http://codereview.stackexchange.com/a/70197/35991
for a nice explanation).
However, the performance improvement was almost not significantmeasurable (0.01 instead of 0.011 seconds). Exponentiation by repeated squaring probably pays off only for
larger numbers and exponents.