VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-sum-arithmetic-series/

⇱ Program for sum of arithmetic series - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program for sum of arithmetic series

Last Updated : 26 May, 2026

A series with same common difference is known as arithmetic series. The first term of series is 'a' and common difference is d. The series looks like a, a + d, a + 2d, a + 3d, . . . Find the sum of series upto nth term.

Examples:

Input: n = 5, a = 1, d = 3
Output: 35
Explanation: Series upto 5th term is1 4 7 10 13, so sum will be 35.

Input: n = 3, a = 1, d = 2
Output: 9
Example: Series upto 3rd term is 1 3 5, so sum will be 9.

[Naive Approach] Using Iteration – O(n) Time and O(1) Space

The idea is to generate each term of the Arithmetic Progression one by one and keep adding it to the final sum. Starting from the first term, we repeatedly add the common difference to obtain the next term until all n terms are processed.

  • Initialize the sum as 0
  • Iterate n times to generate all AP terms
  • Add the current term to the sum and update it using common difference
  • Return the final accumulated sum

Output
230

[Optimal Approach] Using Arithmetic Progression Formula – O(1) Time and O(1) Space

The idea is to directly use the mathematical formula for the sum of an Arithmetic Progression instead of generating each term individually. Since the first term, common difference, and number of terms are known, the sum can be computed in constant time using the AP sum formula.

Sum of arithmetic series = ((n / 2) * (2 * a + (n - 1) * d))
Where: a - First term, d - Common difference, n - No of terms

How does this formula work?
We can prove the formula using mathematical induction. We can easily see that the formula holds true for n = 1 and n = 2. Let this be true for n = k-1.

Let the formula be true for n = k - 1.
Sum of first (k - 1) elements of arithmetic series: = ((k - 1) / 2) × [2a + (k - 2)d]

We know the k-th term of arithmetic series is: Tk = a + (k - 1)d

Sum of first k elements:= Sum of first (k - 1) elements + k-th element
= [((k - 1) / 2) × (2a + (k - 2)d)] + [a + (k - 1)d]
= { (k - 1)(2a + (k - 2)d) + 2a + 2(k - 1)d } / 2
= { 2ak - 2a + k²d - 3kd + 2d + 2a + 2kd - 2d } / 2
= { 2ak + k²d - kd } / 2
= { k(2a + (k - 1)d) } / 2
= (k / 2) × [2a + (k - 1)d]

Example:


Output
230
Comment