Sum of powers

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 ainstead 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]
1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 2.00 out of 5)
Loading...
Subscribe
We send about one email per week with our latest tutorials and updates
Never display this again :)