# How to find sum of the series 2+ 10+ 18+.... n in Python?

I'm a new learner and wondering how to do it. I can do it in c programming

12/2/2019 3:58:55 PM

Ishmum Tahzeeb17 Answers

New AnswerYou just need to use range() and sum() : result = sum(range(2, n, 8)) where n is the ending value. In case you don't know, the third argument of range() is optional (it defaults to 1) and it is the step used to output values from 2 to n, giving you 2, 2+8, 2+8+8,..., until the last 2+8k that is smaller than n. Happy coding!

The easiest solution is this: num_list=[2, 4,3,5,1] sum(num_list) # returns sum of the number elements of the num_list.

Unless Python optimizes for this, it might be faster computationally to use the mathematical shortcut for an arithmetic series Sq= q*(a1 + aq) /2. In this case the nth term, n = 2+(q-1)*8. So with the correction from thoq! below, result=((n + 4)**2 - 4) /16 Here's code showing equivalence to sum(range(2,1000,8)), up to n=994. I haven't timed the two methods yet: https://code.sololearn.com/c9XMNrJqtmRf/?ref=app Or in terms of the qth term: result= (4 *q**2)-2*q I'll time this at some point to see if there's any speed difference compared to writing out the sum of a range. I'm guessing there won't be much. https://m.wikihow.com/Find-the-Sum-of-an-Arithmetic-Sequence

Hope J Your formula doesn't seem to work. This one does (I am sure it could be simplified): res = 8*(((n-2)/8 + 1)*(n-2)/8/2)+2*((n-2)/8)+2 Gonçalo Magalhaes It needs to be like this: sum(range(2,n+1,8)) Otherwise n is excluded from the sum.

I will not give you the exact code. What you do is 1. Define an empty list and the variable, say x, with value 2 2. While loop till x is not equal to n, adding 8 to x each time. 3. In each loop, add the new value of x to the list 4. In the end, find the sum of the list Hope I was clear and also that i understood what you want correctly

https://code.sololearn.com/clL46z1HnD25/?ref=app hope that helps. Just a suggestion, you should try yourself also

It works for me. n is the number of terms in the series (including the initial '2'). a(n) is the n'th term, s(n) is the sum of the first n terms. The formula I gave simplifies to: 4n^2-2n. n=1: 2 = 2. s(n)=4(1^2)-2(1) = 4-2= 2. n=2: 2 + 10 = 12. s(n)=4(2^2)-2(2)= 16 - 4 =12. n=3: 2 + 10 + 18 = 30. s(n)=4(3^2)-2(3)=4(9)-6=30. n=4: 2+10+18+26=56. s(n)=4(4^2)-2(4)=56. more generally, if you assume s(n) = 4n^2 - 2n, and we know that that the nth term a(n) = 2 + 8(n-1), you can show that s(n+1)=s(n)+a(n+1), so qed by induction.

Hope J I just tried your formula. Now that I am looking more closely at it I can see that it doesn't work because you were mixing up the variables as they were given in the task. There n is the last number in the series and not the count of numbers in the series.

Ok right. I think the right formula then is s(n) = [(n + 4)^2 - 4]/16. I only verified up to n=26 (four terms) .