C/C++ Program to Find the sum of Series with the n-th term as n^2 – (n-1)^2

This program finds the sum of a mathematical series where the n-th term is defined as Tn = n2 - (n-1)2. We need to calculate the sum Sn = T1 + T2 + T3 + ... + Tn modulo (109 + 7).

Syntax

result = ((n % mod) * (n % mod)) % mod;

Mathematical Derivation

First, let's simplify the term Tn

T<sub>n</sub> = n<sup>2</sup> - (n-1)<sup>2</sup>
T<sub>n</sub> = n<sup>2</sup> - (n<sup>2</sup> - 2n + 1)
T<sub>n</sub> = n<sup>2</sup> - n<sup>2</sup> + 2n - 1
T<sub>n</sub> = 2n - 1

Now we can find the sum of the series −

S<sub>n</sub> = ?(2n - 1) = 2?n - ?1 = 2 * n(n+1)/2 - n = n(n+1) - n = n<sup>2</sup>

Therefore, Sn = n2. Since the result can be very large, we use modular arithmetic.

Example

#include <stdio.h>
#define MOD 1000000007

int main() {
    long long n = 229137999;
    
    /* Calculate n^2 mod (10^9 + 7) using modular multiplication */
    long long result = ((n % MOD) * (n % MOD)) % MOD;
    
    printf("Input: %lld\n", n);
    printf("Output: %lld\n", result);
    
    return 0;
}
Input: 229137999
Output: 218194447

How It Works

  • We simplify Tn = n2 - (n-1)2 to Tn = 2n - 1
  • The sum of the series becomes Sn = n2
  • We use modular arithmetic property: (a * b) % k = ((a % k) * (b % k)) % k
  • This prevents integer overflow for large values of n

Conclusion

The sum of the series with Tn = n2 - (n-1)2 simplifies to n2. Using modular arithmetic ensures we can handle large input values efficiently without overflow.

Updated on: 2026-03-15T11:41:03+05:30

396 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements