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

Here we will see how to get the sum of the series with n-th term as n2 − (n−1)2. The recurrence relation is like below −

Tn = n2 − (n−1)2

So the series is −

S = T? + T? + T? + ... + T? S = (1² - 0²) + (2² - 1²) + (3² - 2²) + ... + (n² - (n-1)²) S = 1 + 3 + 5 + ... + (2n-1) = n²

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

Syntax

long long getSum(long long n);

Mathematical Derivation

The series simplifies to a telescoping sum. When we expand each term −

  • T? = 1² - 0² = 1
  • T? = 2² - 1² = 4 - 1 = 3
  • T? = 3² - 2² = 9 - 4 = 5
  • T? = 4² - 3² = 16 - 9 = 7

This gives us the sum of first n odd numbers, which equals n².

Example

#include <stdio.h>
#define MOD 1000000007

long long getSum(long long n) {
    return ((n % MOD) * (n % MOD)) % MOD;
}

int main() {
    long long n = 56789;
    printf("Sum of series for n = %lld: %lld\n", n, getSum(n));
    
    /* Testing with smaller values */
    printf("For n = 5: %lld\n", getSum(5));
    printf("For n = 10: %lld\n", getSum(10));
    
    return 0;
}

Output

Sum of series for n = 56789: 224990500
For n = 5: 25
For n = 10: 100

Key Points

  • The telescoping sum simplifies the series to n²
  • We use modular arithmetic to prevent integer overflow
  • Time complexity is O(1) and space complexity is O(1)

Conclusion

The sum of the series with n-th term as n² - (n-1)² equals n². Using modular arithmetic ensures we handle large values efficiently while maintaining the mathematical correctness of the solution.

Updated on: 2026-03-15T11:39:55+05:30

232 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements