
Problem
Solution
Submissions
sum of the series '1 + 1/2 + 1/3 + ... + 1/n'
Certification: Basic Level
Accuracy: 40%
Submissions: 5
Points: 5
Write a C# program to implement the HarmonicSum(int n) function, which calculates the sum of the harmonic series 1 + 1/2 + 1/3 + ... + 1/n for a given positive integer n. The function should return the sum as a double value.
Example 1
- Input: n = 4
- Output: 2.0833333333333335
- Explanation: For n = 4, we calculate 1 + 1/2 + 1/3 + 1/4
- = 1 + 0.5 + 0.33333 + 0.25
- = 2.08333...
Example 2
- Input: n = 10
- Output: 2.9289682539682538
- Explanation: For n = 10, we calculate 1 + 1/2 + 1/3 + ... + 1/10
- The sum equals approximately 2.92897
Constraints
- 1 ≤ n ≤ 10^6
- The result should be calculated with double precision
- 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
- Add the term 1/i to a running sum for each iteration
- Be careful with integer division; ensure you're using floating-point arithmetic
- Consider using mathematical properties for large values of n to optimize performance