Harmonic series
This page uses content from Wikipedia. The original article was at Harmonic number. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) |
In mathematics, the n-th harmonic number is the sum of the reciprocals of the first n natural numbers:
- Hn = 1 + 1/2 + 1/3 + ... + 1/n
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.
- Task
- Write a function (routine, procedure, whatever it may be called in your language) to generate harmonic numbers.
- Use that procedure to show the values of the first 20 harmonic numbers.
- Find and show the position in the series of the first value greater than the integers 1 through 5
- Stretch
- Find and show the position in the series of the first value greater than the integers 6 through 10
Raku
<lang perl6>use Lingua::EN::Numbers;
my @H = [\+] (1..*).map: { FatRat.new( 1, $_ ) };
say "First twenty harmonic numbers as rationals:\n",
@H[^20].&ratty.batch(5)».fmt("%18s").join: "\n";
say "\nOne Hundredth:\n", @H[99].&ratty[0];
say "\n(zero based) Index of first value:"; printf " greater than %2d: %6s (%s term)\n",
$_, comma( my $i = @H.first( * > $_, :k) ), ordinal 1 + $i for 1..10;
sub ratty (*@a) {
@a.map: { .narrow.^name eq 'Int' ?? .narrow !! .nude.join('/') }
}</lang>
- Output:
First twenty harmonic numbers as rationals: 1 3/2 11/6 25/12 137/60 49/20 363/140 761/280 7129/2520 7381/2520 83711/27720 86021/27720 1145993/360360 1171733/360360 1195757/360360 2436559/720720 42142223/12252240 14274301/4084080 275295799/77597520 55835135/15519504 One Hundredth: 14466636279520351160221518043104131447711/2788815009188499086581352357412492142272 (zero based) Index of first value: greater than 1: 1 (second term) greater than 2: 3 (fourth term) greater than 3: 10 (eleventh term) greater than 4: 30 (thirty-first term) greater than 5: 82 (eighty-third term) greater than 6: 226 (two hundred twenty-seventh term) greater than 7: 615 (six hundred sixteenth term) greater than 8: 1,673 (one thousand, six hundred seventy-fourth term) greater than 9: 4,549 (four thousand, five hundred fiftieth term) greater than 10: 12,366 (twelve thousand, three hundred sixty-seventh term)