nthHarmonicNumber function

double nthHarmonicNumber(
  1. int n
)

Returns the nth harmonic number n.

The nth harmonic number is the sum of the reciprocals of the first n natural numbers.

Example:

final result = nthHarmonicNumber(5);
print(result); // prints: 2.283333333333333

Implementation

double nthHarmonicNumber(int n) {
  double harmonic = 0.0;
  for (int i = 1; i <= n; i++) {
    harmonic += 1 / i.toDouble();
  }
  return harmonic;
}