Home > Back-end >  Summation of multiples
Summation of multiples

Time:05-11

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 sumOfMultiples that has two integer parameters x and n. The method does not return an Integer. The sumOfMultiples function will compute a summation of multiples and display the result on the screen.

The sum of multiples is computed for parameters x and n as follows: sum = 1 x 2x 3x ... nx

Example: sumOfMultiples(3,5);

Expected output: 46

CodePudding user response:

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

CodePudding user response:

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)

CodePudding user response:

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)
  • Related