Summation of numbers in a sequence
Write a python program to sum of N natural numbers [even,odd,divisible by n]
So, the immediate way to solve this is by putting it in a loop, use flow control to weed out the unnecessary values.
You can also use range to generate the progression.
But using formula for summation of numbers in a sequence,summation for even large values of N can be done efficiently.
What is a natural number?
0 is usually considered a whole number and excluded from inclusion in the natural numbers.
So numbers 1,2,3,... are considered natural numbers.
Program using a loop
N = 25
sum=0
for num in range(N+1):
sum+=num
print("Sum of first",N,"natural numbers is",sum)
Output
https://www.math-only-math.com/arithmetic-progression.html
General form of arithmetic progression: a = a + (n - 1)d.
Therefore, nth term of an Arithmetic Progress whose first term = ‘a’ and common difference = ‘d’ is a = a + (n - 1)d.
Sum of first n terms in an arithmetic progression.
https://www.math-only-math.com/sum-of-the-first-n-terms-of-an-arithmetic-progression.html
S =n/2 [2a + (n - 1)d]
a=1, d=1
S= n/2[2+n-1]
S = n/2[n+1]
>>> n=25
>>> for i in range(1,n+1):
... sum+=i
>>>sum
325
Using the formula
>>> (n/2)*(n+1)
325.0
Sum of first n odd terms in an arithmetic progression.
S =n/2 [2a + (n - 1)d]
a=1, d = 2
S=n/2[2+(n-1)2]
S=n/2[2+2n-2]
S=n/2[2n]
S=n*n
>>> for i in range(1,(n*2)+1,2):
... sum+=i
...
>>> sum
625
Using the formula
>>> n*n
625
Sum of first n even terms in an arithmetic progression.
S =n/2 [2a + (n - 1)d]
a=2, d=2
S=n/2[4+(n-1)2]
S=n/2[4+2n-2]
S=n/2[2+2n]
S= n[1+n]
S=n*(1+n)
>>>n=25
>>> sum_even=0
>>> for i in range(2, (n*2)+1,2):
... sum_even+=i
...
>>> sum_even
650
Using formula:
>>>n=25
>>> n*(1+n)
650
Sum of first n divisible by k terms in an arithmetic progression.
S =n/2 [2a + (n - 1)d]
a=k d=k
S=n/2[2k+(n-1)k]
S = nk+[nk(n-1)] / 2
S= nk(1+(n-1)/2)
S=nk[(n+1)/2]
>>> for i in range(k,(n*k)+1,k):
... sum_divk+=i
...
>>> sum_divk
975
Using the formula:
>>> n*k * ( (n+1) /2 )
975.0
Comments
Post a Comment