'Summation of multiples

I am learning python and can't get my head around this program. I just can't seem to find the right loop to get the result.

Q:Create a Python function named sum Of Multiples that has two integer parameters x and n.

Example:sum Of Multiples(3,5);

Expected output:46



Solution 1:[1]

This is simple math, the sum is equivalent to 1 + x*(1+2+3+...+n), so 1 + x*(n*(n+1)//2):

def sumOfMultiples(x,n):
    print(1+x*n*(n+1)//2)
    
sumOfMultiples(3, 5)
46

Solution 2:[2]

sum = 1 + x + 2x + 3x + ... + 

could be written as sum = 1+x(0+1+2+3+...)

so just use a for loop from 0 to n or n+1 depending on where you're supposed to stop and multiply the result with x. Or even shorter use sum and range:

def sumOfMultiples(x, n):
    print(1+sum(range(n+1))*x)

Solution 3:[3]

The question basically is asking you to sum all n mutliples of x. So just do this,

def sumOfMultiples(x, n):
  m_sum = 1
  for i in range(1, n+1):
    m_sum += i*x
  return m_sum

sumOfMultiples(3,5)

You can also do this,

sumOfMultiples = lambda x,n: sum([1] + [x*i for i in range(1, n+1)])
sumOfMultiples(3,5)

Solution 4:[4]

Let's just say this should get the job done, but not really optimized:

def sumOfMultiples(x,n): 
    x_muti = [1]
    for i in range(1,n+1):
        x_muti.append(x*i)
    print(sum(x_muti))
    
sumOfMultiples(3,5)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mozway
Solution 2
Solution 3
Solution 4 richardec