Saturn
Saturn

Reputation: 27

Write a python script to calculate sum of following series :

I am trying to calculate the sum of the series below but am not able to get the correct value of sum

s = (1) + (1+2) + (1+2+n)

I've used the following code

s = 0
n = int(input("Enter number : "))
for i in range (1,n+1):
        s  = s + 1 +i
print (s) 

for n = 3 the output should be 10

Upvotes: 0

Views: 958

Answers (2)

Djaouad
Djaouad

Reputation: 22794

After some analysis, it turns out there is a formula for that sum (you can simplify it further):

enter image description here

Coded:

def S(n):
  return (n + 1) * (4 * n ** 2 + 8 * n) // 24

print(S(3))

Output:

10
35
220

So your code becomes as follows (without a function):

n = int(input("Enter number : "))
s = (n + 1) * (4 * n ** 2 + 8 * n) // 24
print(s)

You can do it the hard way, without a formula (with loops):

s = 0
n = int(input("Enter number : "))
for i in range (1, n + 1):
  for j in range(1, i + 1):
    s = s + j
print(s)

Upvotes: 1

prashanth basani
prashanth basani

Reputation: 53

Without the formula, a shorter version of MrGreek's way

sum_=0 
n = 4
for i in range(n+1):
    sum_ = sum_ + sum(range(i+1))
print(sum_)

Upvotes: 1

Related Questions