You 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.
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:
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.
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
It needs to be like this:
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
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.
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.