Python Program to Find Sum of Series 1+2+3+...+n
You can find the sum of the series 1+2+3+...+n in Python using the formula
sum = n * (n + 1) // 2 or by looping from 1 to n and adding each number.Examples
Input5
Output15
Input10
Output55
Input1
Output1
How to Think About It
To find the sum of numbers from 1 to n, think of adding all numbers one by one or use the shortcut formula that multiplies n by (n plus 1) and divides by 2. This formula works because the series is an arithmetic progression with a difference of 1.
Algorithm
1
Get the input number n.2
Calculate the sum using the formula sum = n * (n + 1) // 2.3
Print or return the sum.Code
python
n = int(input('Enter a positive integer: ')) sum_series = n * (n + 1) // 2 print('Sum of series 1 to', n, 'is:', sum_series)
Output
Enter a positive integer: 5
Sum of series 1 to 5 is: 15
Dry Run
Let's trace the example where n=5 through the code.
1
Input
User enters n = 5
2
Calculate sum
sum_series = 5 * (5 + 1) // 2 = 5 * 6 // 2 = 30 // 2 = 15
3
Output
Print 'Sum of series 1 to 5 is: 15'
| n | Calculation | sum_series |
|---|---|---|
| 5 | 5 * (5 + 1) // 2 | 15 |
Why This Works
Step 1: Use of formula
The formula n * (n + 1) // 2 calculates the sum of the first n natural numbers quickly without looping.
Step 2: Integer division
Using // ensures the result is an integer since the sum of natural numbers is always whole.
Step 3: Input and output
The program takes input from the user and prints the sum clearly.
Alternative Approaches
Using a for loop
python
n = int(input('Enter a positive integer: ')) sum_series = 0 for i in range(1, n + 1): sum_series += i print('Sum of series 1 to', n, 'is:', sum_series)
This method is easy to understand but slower for large n compared to the formula.
Using recursion
python
def sum_series(n): if n == 1: return 1 else: return n + sum_series(n - 1) n = int(input('Enter a positive integer: ')) print('Sum of series 1 to', n, 'is:', sum_series(n))
Recursion shows a different approach but can cause stack overflow for very large n.
Complexity: O(1) time, O(1) space
Time Complexity
Using the formula takes constant time because it performs only a few arithmetic operations regardless of n.
Space Complexity
The formula uses constant space as it stores only a few variables.
Which Approach is Fastest?
The formula method is fastest and most efficient compared to looping or recursion, which take O(n) time.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Formula | O(1) | O(1) | Fastest for any n |
| For loop | O(n) | O(1) | Easy to understand, small n |
| Recursion | O(n) | O(n) | Learning recursion, small n |
Use the formula
n * (n + 1) // 2 for the fastest and simplest sum calculation.Beginners often forget to use integer division
//, which can cause the result to be a float.