Skip to content

Instantly share code, notes, and snippets.

@lulu-berlin
Last active August 5, 2017 17:15
Show Gist options
  • Select an option

  • Save lulu-berlin/6a4107ad2581f58f14ca718d8d14d6dc to your computer and use it in GitHub Desktop.

Select an option

Save lulu-berlin/6a4107ad2581f58f14ca718d8d14d6dc to your computer and use it in GitHub Desktop.
Harmonic numbers
/*
* A minimalist implementation of a harmonic number calculation function in ES6
*
* harmonicNumber(n: number) => number
*
* returns the sum of: 1 + 1/2 + 1/3 + ... + 1/n
*
* It assumes that n is an integer greater than zero.
*
* See: Donald E. Knuth, The Art of Programming, vol. 1, §1.2.7
*/
export const harmonicNumber = (n, r = 0) => {
while (n > 0) r += 1 / n--;
return r;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment