For a given n
and m
, compute the sum sigma = 1^n + 2^n + 3^n + ... + m^n
and print it.
Example
Input:
let n = 2
let m = 5
Expected value/output:
55
[collapse]
Hint
Change the function for computing powers of 2, to compute powers of a
instead and add them up to m
.
[collapse]
Solution
let n = 2
let m = 5
func powaN(N:Int, a:Int) -> Int {
if N == 0 {
return 1
}
else {
var halfN = N/2
var halfpowaN = powaN(N: halfN, a: a)
var res = halfpowaN * halfpowaN
if N - halfN > halfN {
res *= a
}
return res
}
}
func sumOfPowers(N:Int, M:Int) -> Int {
var sum = 0
for i in 1...M {
sum += powaN(N:N, a:i)
}
return sum
}
print(sumOfPowers(N:n, M:m))
[collapse]