Thursday, September 4, 2025
HomeData Modelling & AIPython Program for Find sum of Series with n-th term as n^2...

Python Program for Find sum of Series with n-th term as n^2 – (n-1)^2

We are given an integer n and n-th term in a series as expressed below:

Tn = n2 - (n-1)2

We need to find Sn mod (109 + 7), where Sn is the sum of all of the terms of the given series and,

Sn = T1 + T2 + T3 + T4 + ...... + Tn

Examples:

Input : 229137999
Output : 218194447

Input : 344936985
Output : 788019571

Let us do some calculations, before writing the program. Tn can be reduced to give 2n-1 . Let\’s see how:

Given, Tn = n2 - (n-1)2
Or, Tn =  n2 - (1 + n2 - 2n)
Or, Tn =  n2 - 1 - n2 + 2n
Or, Tn =  2n - 1. 

Now, we need to find ∑Tn.

∑Tn = ∑(2n – 1)

We can simplify the above formula as, ∑(2n – 1) = 2*∑n – ∑1 Or, ∑(2n – 1) = 2*∑n – n. Where, ∑n is the sum of first n natural numbers. We know the sum of n natural number = n(n+1)/2. Therefore, putting this value in the above equation we will get,

∑Tn = (2*(n)*(n+1)/2)-n = n2

Now the value of n2 can be very large. So instead of direct squaring n and taking mod of the result. We will use the property of modular multiplication for calculating squares:

(a*b)%k = ((a%k)*(b%k))%k

Python3




# Python program to find sum of given
# series.
  
mod = 1000000007
def findSum(n):
    return ((n % mod) * (n % mod)) % mod
      
      
# main()
n = 229137999    
print (findSum(n))
  
# Contributed by _omg


Output:

218194447

Time Complexity: O(1) 
Auxiliary Space: O(1)

Please refer complete article on Find sum of Series with n-th term as n^2 – (n-1)^2 for more details!

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Dominic
32261 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6626 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6747 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6695 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS