Python Program to Find Arithmetic Progression Sum
sum = n * (2 * a + (n - 1) * d) // 2, where a is the first term, d is the common difference, and n is the number of terms.Examples
How to Think About It
Algorithm
Code
def arithmetic_progression_sum(a, d, n): last_term = a + (n - 1) * d total_sum = n * (a + last_term) // 2 return total_sum # Example usage print(arithmetic_progression_sum(1, 1, 5)) # Output: 15
Dry Run
Let's trace the example where a=1, d=1, n=5 through the code
Calculate last term
last_term = 1 + (5 - 1) * 1 = 1 + 4 = 5
Calculate sum
total_sum = 5 * (1 + 5) // 2 = 5 * 6 // 2 = 30 // 2 = 15
Return sum
return 15
| Step | last_term | total_sum |
|---|---|---|
| Calculate last term | 5 | |
| Calculate sum | 5 | 15 |
| Return sum | 15 |
Why This Works
Step 1: Find the last term
The last term is found by adding the common difference multiplied by (n - 1) to the first term using last_term = a + (n - 1) * d.
Step 2: Calculate the sum
The sum of the arithmetic progression is the number of terms multiplied by the average of the first and last terms: sum = n * (a + last_term) / 2.
Step 3: Return the result
Return the calculated sum as the final output.
Alternative Approaches
def arithmetic_progression_sum_loop(a, d, n): total = 0 for i in range(n): total += a + i * d return total print(arithmetic_progression_sum_loop(1, 1, 5)) # Output: 15
def arithmetic_progression_sum_range(a, d, n): return sum(a + i * d for i in range(n)) print(arithmetic_progression_sum_range(1, 1, 5)) # Output: 15
Complexity: O(1) time, O(1) space
Time Complexity
The formula method calculates the sum using a fixed number of operations regardless of n, so it runs in constant time O(1).
Space Complexity
It uses only a few variables and no extra data structures, so space complexity is O(1).
Which Approach is Fastest?
The formula method is fastest and most efficient. Loop-based methods take O(n) time and are slower for large n.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Formula method | O(1) | O(1) | Large n, fast calculation |
| Loop method | O(n) | O(1) | Small n, simple understanding |
| Sum with range | O(n) | O(1) | Pythonic, readable for small n |