Search code examples
pythonmathsum

I need help doing this double summation in python


I'm pretty new in python and I'm having trouble doing this double summation.

Summation

I already tried using

x = sum(sum((math.pow(j, 2) * (k+1)) for k in range(1, M-1)) for j in range(N))

and using 2 for loops but nothing seens to work


Solution

  • You were pretty close:

    N = int(input("N: "))
    M = int(input("M: "))
    
    x = sum(sum(j ** 2 * (k + 1) for k in range(M)) for j in range(1, N + 1))
    

    It also can be done with nested for loops:

    x = 0
    for j in range(1, N + 1):  # [1, N]
        for k in range(M):  # [0, M - 1]
            x += j ** 2 * (k + 1)