
Problem
Solution
Submissions
Sum of the Series '1 + 1/2 + 1/3 + ... + 1/n'
Certification: Basic Level
Accuracy: 100%
Submissions: 3
Points: 5
Write a C++ program that calculates the sum of the series `1 + 1/2 + 1/3 + ... + 1/n`, where `n` is a positive integer provided by the user.
Example 1
- Input: n = 5
- Output: 2.28333
- Explanation:
- Step 1: Calculate each term in the series: 1 + 1/2 + 1/3 + 1/4 + 1/5.
- Step 2: 1 + 0.5 + 0.33333 + 0.25 + 0.2 = 2.28333.
- Step 3: Return 2.28333 as the final sum of the harmonic series up to n = 5.
Example 2
- Input: n = 10
- Output: 2.92897
- Explanation:
- Step 1: Calculate each term in the series: 1 + 1/2 + 1/3 + ... + 1/10.
- Step 2: 1 + 0.5 + 0.33333 + 0.25 + 0.2 + 0.16667 + 0.14286 + 0.125 + 0.11111 + 0.1 = 2.92897.
- Step 3: Return 2.92897 as the final sum of the harmonic series up to n = 10.
Constraints
- 1 ≤ n ≤ 10^6
- Time Complexity: O(n)
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use a loop to iterate from 1 to `n`.
- In each iteration, add the reciprocal of the current number to the sum.
- Handle edge cases where `n` is 1 separately.