How to resolve the algorithm Harmonic series step by step in the Nim programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Harmonic series step by step in the Nim programming language
Table of Contents
Problem Statement
In mathematics, the n-th harmonic number is the sum of the reciprocals of the first n natural numbers: The series of harmonic numbers thus obtained is often loosely referred to as the harmonic series. Harmonic numbers are closely related to the Riemann zeta function, and roughly approximate the natural logarithm function; differing by γ (lowercase Gamma), the Euler–Mascheroni constant. The harmonic series is divergent, albeit quite slowly, and grows toward infinity.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Harmonic series step by step in the Nim programming language
Source code in the nim programming language
import strformat
iterator h(): (int, float) =
## Yield the index of the term and its value.
var n = 1
var r = 0.0
while true:
r += 1 / n
yield (n, r)
inc n
echo "First 20 terms of the harmonic series:"
for (idx, val) in h():
echo &"{idx:2}: {val}"
if idx == 20: break
echo()
var target = 1.0
for (idx, val) in h():
if val > target:
echo &"Index of the first term greater than {target.int:2}: {idx}"
if target == 10: break
else: target += 1
import strformat
import bignum
iterator h(): (int, Rat) =
var n = 1
var r = newRat()
while true:
r += newRat(1, n)
yield (n, r)
inc n
echo "First 20 terms of the harmonic series:"
for (idx, val) in h():
echo &"{idx:2}: {val}"
if idx == 20: break
echo()
var target = 1
for (idx, val) in h():
if val > target:
echo &"Index of the first term greater than {target:2}: {idx}"
if target == 10: break
else: inc target
You may also check:How to resolve the algorithm Stack step by step in the C# programming language
You may also check:How to resolve the algorithm K-d tree step by step in the Racket programming language
You may also check:How to resolve the algorithm Find palindromic numbers in both binary and ternary bases step by step in the Mathematica/Wolfram Language programming language
You may also check:How to resolve the algorithm Knuth shuffle step by step in the AutoHotkey programming language
You may also check:How to resolve the algorithm General FizzBuzz step by step in the XPL0 programming language