Python Program to Find Sum of Series 1/1+1/2+1/3+...+1/n
sum_series = 0; for i in range(1, n+1): sum_series += 1/i.Examples
How to Think About It
Algorithm
Code
n = int(input("Enter the number of terms: ")) sum_series = 0.0 for i in range(1, n + 1): sum_series += 1 / i print(f"Sum of series up to {n} terms is {sum_series}")
Dry Run
Let's trace the program for n=5 through the code
Input
User enters n = 5
Initialize sum
sum_series = 0.0
Loop iteration 1
i=1, sum_series = 0.0 + 1/1 = 1.0
Loop iteration 2
i=2, sum_series = 1.0 + 1/2 = 1.5
Loop iteration 3
i=3, sum_series = 1.5 + 1/3 ≈ 1.8333
Loop iteration 4
i=4, sum_series = 1.8333 + 1/4 = 2.0833
Loop iteration 5
i=5, sum_series = 2.0833 + 1/5 = 2.2833
Print result
Output: Sum of series up to 5 terms is 2.283333333333333
| i | sum_series |
|---|---|
| 1 | 1.0 |
| 2 | 1.5 |
| 3 | 1.8333333333333333 |
| 4 | 2.083333333333333 |
| 5 | 2.283333333333333 |
Why This Works
Step 1: Initialize sum
We start with sum_series = 0.0 because we have not added any terms yet.
Step 2: Add each term
For each number from 1 to n, we add 1/i to the sum to include that term in the series.
Step 3: Final sum
After the loop finishes, sum_series holds the total sum of all terms from 1 to n.
Alternative Approaches
n = int(input("Enter the number of terms: ")) sum_series = 0.0 i = 1 while i <= n: sum_series += 1 / i i += 1 print(f"Sum of series up to {n} terms is {sum_series}")
n = int(input("Enter the number of terms: ")) sum_series = sum(1 / i for i in range(1, n + 1)) print(f"Sum of series up to {n} terms is {sum_series}")
Complexity: O(n) time, O(1) space
Time Complexity
The program runs a single loop from 1 to n, so it performs n additions, making it O(n).
Space Complexity
Only a few variables are used to store the sum and loop counter, so space is O(1).
Which Approach is Fastest?
All approaches use a single loop or generator expression, so they have similar speed; the generator expression is concise but may be slightly slower due to function call overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| For loop | O(n) | O(1) | Clear and simple for beginners |
| While loop | O(n) | O(1) | Alternative loop style |
| Generator expression with sum | O(n) | O(1) | Concise and Pythonic |