Harmonic Sum - Problem

Calculate the harmonic sum for a given positive integer N.

The harmonic sum is defined as: 1 + 1/2 + 1/3 + 1/4 + ... + 1/N

Display the result rounded to 6 decimal places.

Input & Output

Example 1 — Small Case
$ Input: n = 3
Output: 1.833333
💡 Note: Harmonic sum = 1/1 + 1/2 + 1/3 = 1.000000 + 0.500000 + 0.333333 = 1.833333
Example 2 — Single Term
$ Input: n = 1
Output: 1.000000
💡 Note: Harmonic sum = 1/1 = 1.000000
Example 3 — Larger Case
$ Input: n = 5
Output: 2.283333
💡 Note: 1/1 + 1/2 + 1/3 + 1/4 + 1/5 = 1 + 0.5 + 0.333333 + 0.25 + 0.2 = 2.283333

Constraints

  • 1 ≤ n ≤ 106
  • Result must be displayed to exactly 6 decimal places

Visualization

Tap to expand
Harmonic Sum CalculatorINPUTALGORITHM STEPSFINAL RESULTN = 5Calculate harmonic sumfor first 5 terms1Initialize sum = 0.02Loop i from 1 to 53Add 1/i to running sum4Format to 6 decimals1/1 + 1/2 + 1/3 + 1/4 + 1/5= 1 + 0.5 + 0.333 + 0.25 + 0.22.283333Harmonic Sum ResultSum of reciprocalsfrom 1 to NKey Insight:The harmonic series requires computing every term 1/i - no mathematical shortcut exists,so a simple accumulating loop is both the most intuitive and optimal solution.TutorialsPoint - Harmonic Sum | Simple Loop Accumulation
Asked in
Accenture 15 TCS 12 Infosys 8
12.5K Views
Medium Frequency
~5 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen