Tutorialspoint
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)
NumberControl StructuresTech MahindraDropbox
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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.

Steps to solve by this approach:

 Step 1: Define a function sum_of_series that takes an integer n.

 Step 2: Initialize a sum variable to 0.0.
 Step 3: Use a for loop from i=1 to i=n.
 Step 4: For each iteration, add 1.0/i to the sum.
 Step 5: Return the final sum.

Submitted Code :