Harmonic series: Difference between revisions

Add bruijn
(add FreeBASIC)
(Add bruijn)
 
(38 intermediate revisions by 22 users not shown)
Line 1:
{{draft task}}
{{Wikipedia|Harmonic number}}
 
Line 34:
=={{header|ALGOL 68}}==
Using standard lenghth REAL numbers this can find the first Harmonic number > 10, would probably need higher precision to find Harmonic numbers with larger values.
<langsyntaxhighlight lang="algol68">BEGIN # find some harmonic numbers, Hn is the sum if the reciprocals of 1..n #
# returns the first n Harmonic numbers #
OP HARMONIC = ( INT n )[]REAL:
Line 62:
FI
OD
END</langsyntaxhighlight>
{{out}}
<pre>
Line 95:
Position of the first harmonic number > 9: 4550
Position of the first harmonic number > 10: 12367
</pre>
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">H: function [n][
sum map 1..n => reciprocal
]
 
firstAbove: function [lim][
i: 1
while ø [
if lim < to :floating H i ->
return i
i: i + 1
]
]
 
print "The first 20 harmonic numbers:"
print map 1..20 => H
 
print ""
loop 1..4 'l [
print ["Position of first term >" l ":" firstAbove l]
]</syntaxhighlight>
 
{{out}}
 
<pre>The first 20 harmonic numbers:
1/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
 
Position of first term > 1 : 2
Position of first term > 2 : 4
Position of first term > 3 : 11
Position of first term > 4 : 31</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f HARMONIC_SERIES.AWK
# converted from FreeBASIC
BEGIN {
limit = 20
printf("The first %d harmonic numbers:\n",limit)
for (n=1; n<=limit; n++) {
h += 1/n
printf("%2d %11.8f\n",n,h)
}
print("")
h = 1
n = 2
for (i=2; i<=10; i++) {
while (h < i) {
h += 1/n
n++
}
printf("The first harmonic number > %2d is %11.8f at position %d\n",i,h,n-1)
}
exit(0)
}
</syntaxhighlight>
{{out}}
<pre>
The first 20 harmonic numbers:
1 1.00000000
2 1.50000000
3 1.83333333
4 2.08333333
5 2.28333333
6 2.45000000
7 2.59285714
8 2.71785714
9 2.82896825
10 2.92896825
11 3.01987734
12 3.10321068
13 3.18013376
14 3.25156233
15 3.31822899
16 3.38072899
17 3.43955252
18 3.49510808
19 3.54773966
20 3.59773966
 
The first harmonic number > 2 is 2.08333333 at position 4
The first harmonic number > 3 is 3.01987734 at position 11
The first harmonic number > 4 is 4.02724520 at position 31
The first harmonic number > 5 is 5.00206827 at position 83
The first harmonic number > 6 is 6.00436671 at position 227
The first harmonic number > 7 is 7.00127410 at position 616
The first harmonic number > 8 is 8.00048557 at position 1674
The first harmonic number > 9 is 9.00020806 at position 4550
The first harmonic number > 10 is 10.00004301 at position 12367
</pre>
 
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
The [[#MSX_BASIC|MSX BASIC]] solution works without any changes.
==={{header|BASIC256}}===
<syntaxhighlight lang="freebasic">h = 0.0
 
print "The first twenty harmonic numbers are:"
for n = 1 to 20
h += 1.0 / n
print n, h
next n
print
 
h = 1 : n = 2
for i = 2 to 10
while h < i
h += 1.0 / n
n += 1
end while
print "The first harmonic number greater than "; i; " is "; h; ", at position "; n-1
next i
end</syntaxhighlight>
 
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
{{works with|GW-BASIC}}
{{works with|QBasic|1.1}}
{{trans|FreeBASIC}}
<syntaxhighlight lang="qbasic">100 cls
110 print "The first twenty harmonic numbers are:"
120 for n = 1 to 20
130 h = h+(1/n)
140 print n,h
150 next n
160 print
170 h = 1
180 n = 2
190 for i = 2 to 10
200 while h < i
210 h = h+(1/n)
220 n = n+1
230 wend
240 print "The first harmonic number greater than ";i;"is ";h;" at position ";n-1
250 next i
260 end</syntaxhighlight>
 
==={{header|Craft Basic}}===
<syntaxhighlight lang="basic">precision 5
 
print "the first twenty harmonic numbers are:"
 
for n = 1 to 20
 
let h = h + 1 / n
print n, tab, h
 
next n
 
print newline, "the nth index of the first harmonic number that exceeds the nth integer:"
 
let h = 1
let n = 2
 
for i = 2 to 10
 
do
 
if h < i then
 
let h = h + 1 / n
let n = n + 1
 
endif
 
wait
 
loop h < i
 
print tab, n - 1,
 
next i</syntaxhighlight>
{{out| Output}}<pre>
the first twenty harmonic numbers are:
1 1
2 1.50000
3 1.83333
4 2.08333
5 2.28333
6 2.45000
7 2.59286
8 2.71786
9 2.82897
10 2.92897
11 3.01988
12 3.10321
13 3.18013
14 3.25156
15 3.31823
16 3.38073
17 3.43955
18 3.49511
19 3.54774
20 3.59774
 
The nth index of the first harmonic number that exceeds the nth integer:
4 11 31 83 227 616 1674 4550 12375
</pre>
 
==={{header|Gambas}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="vbnet">Public Sub Main()
Dim h As Float = 0
Dim n As Integer, i As Integer
Print "The first twenty harmonic numbers are:"
For n = 1 To 20
h += 1 / n
Print n, h
Next
Print
h = 1
n = 2
For i = 2 To 10
While h < i
h += 1 / n
n += 1
Wend
Print "The first harmonic number greater than "; i; " is "; h; ", at position "; n - 1
Next
End </syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
==={{header|GW-BASIC}}===
The [[#MSX_BASIC|MSX BASIC]] solution works without any changes.
 
==={{header|MSX Basic}}===
{{works with|Applesoft BASIC}}
{{works with|Chipmunk Basic}}
{{works with|PC-BASIC|any}}
{{works with|QBasic}}
<syntaxhighlight lang="qbasic">100 CLS : REM HOME 100 HOME for Applesoft BASIC
110 PRINT "The first twenty harmonic numbers are:"
120 FOR n = 1 TO 20
130 h = h+(1/n)
140 PRINT n,h
150 NEXT n
160 PRINT
170 h = 1
180 n = 2
190 FOR i = 2 TO 10
200 IF NOT(h < i) THEN GOTO 240
210 h = h+(1/n)
220 n = n+1
230 GOTO 200
240 PRINT "The first harmonic number greater than " i "is " h "at position " n-1
250 NEXT i
260 END</syntaxhighlight>
 
==={{header|QBasic}}===
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
<syntaxhighlight lang="qbasic">h = 0!
 
PRINT "The first twenty harmonic numbers are:"
FOR n = 1 TO 20
h = h + 1! / n
PRINT n, h
NEXT n
PRINT
 
h = 1: n = 2
FOR i = 2 TO 10
WHILE h < i
h = h + 1! / n
n = n + 1
WEND
PRINT "The first harmonic number greater than "; i; " is "; h; ", at position "; n - 1
NEXT i
END</syntaxhighlight>
 
==={{header|Run BASIC}}===
{{works with|Just BASIC}}
{{works with|Liberty BASIC}}
<syntaxhighlight lang="vb">print "The first twenty harmonic numbers are:"
for n = 1 to 20
h = h + 1 / n
print n; chr$(9);h ' print n,h for Just BASIC and Liberty BASIC
next n
print
h = 1
n = 2
for i = 2 to 10
while h < i
h = h + 1 / n
n = n +1
wend
print "The first harmonic number greater than ";i; " is ";h;" at position ";n-1
next i
end</syntaxhighlight>
 
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">LET h = 0
 
PRINT "The first twenty harmonic numbers are:"
FOR n = 1 TO 20
LET h = h + 1 / n
PRINT n, h
NEXT n
PRINT
 
LET h = 1
LET n = 2
FOR i = 2 TO 10
DO WHILE h < i
LET h = h + 1 / n
LET n = n + 1
LOOP
PRINT "The first harmonic number greater than "; i; " is "; h; ", at position "; n - 1
NEXT i
END</syntaxhighlight>
 
==={{header|Yabasic}}===
<syntaxhighlight lang="freebasic">h = 0.0
 
print "The first twenty harmonic numbers are:"
for n = 1 to 20
h = h + 1.0 / n
print n, chr$(9), h
next n
print
 
h = 1 : n = 2
for i = 2 to 10
while h < i
h = h + 1.0 / n
n = n + 1
wend
print "The first harmonic number greater than ", i, " is ", h, ", at position ", n-1
next i
end</syntaxhighlight>
 
=={{header|Bruijn}}==
<syntaxhighlight lang="bruijn">
:import std/List .
:import std/Combinator .
:import std/Math/Rational Q
:import std/Number N
 
# fun Church iteration hack
harmonic [0 &[[(Q.add 1 op) : N.++0]] start [[1]]] ⧗ Unary → Rational
op (+1) : N.--0
start (+0.0f) : (+1)
 
custom-gt? &[[[N.gt? 2 (N.mul 0 N.++1)]]] ⧗ Rational → Νumber → Boolean
 
main [φ cons first-20 first-10-above (harmonic <$> (iterate [[[1 (2 1 0)]]] (+0u)))]
first-20 take (+20)
first-10-above [take (+10) first-above]
first-above [find-index [custom-gt? 0 1] 1] <$> (iterate N.inc (+0))
</syntaxhighlight>
 
Takes a *long* time, but will return the correct result.
 
=={{header|C#}}==
{{trans|Go}}
<syntaxhighlight lang="C#">
using System;
using System.Numerics;
 
public class BigRational
{
public BigInteger Numerator { get; private set; }
public BigInteger Denominator { get; private set; }
 
public BigRational(BigInteger numerator, BigInteger denominator)
{
if (denominator == 0)
throw new ArgumentException("Denominator cannot be zero.", nameof(denominator));
 
BigInteger gcd = BigInteger.GreatestCommonDivisor(numerator, denominator);
Numerator = numerator / gcd;
Denominator = denominator / gcd;
 
if (Denominator < 0)
{
Numerator = -Numerator;
Denominator = -Denominator;
}
}
 
public static BigRational operator +(BigRational a, BigRational b)
{
return new BigRational(a.Numerator * b.Denominator + b.Numerator * a.Denominator, a.Denominator * b.Denominator);
}
 
public override string ToString()
{
return $"{Numerator}/{Denominator}";
}
}
 
class Program
{
static BigRational Harmonic(int n)
{
BigRational sum = new BigRational(0, 1);
for (int i = 1; i <= n; i++)
{
BigRational r = new BigRational(1, i);
sum += r;
}
return sum;
}
 
static void Main(string[] args)
{
Console.WriteLine("The first 20 harmonic numbers and the 100th, expressed in rational form, are:");
int[] numbers = new int[21];
for (int i = 1; i <= 20; i++)
{
numbers[i - 1] = i;
}
numbers[20] = 100;
foreach (int i in numbers)
{
Console.WriteLine($"{i,3} : {Harmonic(i)}");
}
 
Console.WriteLine("\nThe first harmonic number to exceed the following integers is:");
const int limit = 10;
for (int i = 1, n = 1; i <= limit; n++)
{
double h = 0;
for (int j = 1; j <= n; j++)
{
h += 1.0 / j;
}
if (h > i)
{
Console.WriteLine($"integer = {i,2} -> n = {n,6} -> harmonic number = {h,9:F6} (to 6dp)");
i++;
}
}
}
}
</syntaxhighlight>
{{out}}
<pre>
The first 20 harmonic numbers and the 100th, expressed in rational form, are:
1 : 1/1
2 : 3/2
3 : 11/6
4 : 25/12
5 : 137/60
6 : 49/20
7 : 363/140
8 : 761/280
9 : 7129/2520
10 : 7381/2520
11 : 83711/27720
12 : 86021/27720
13 : 1145993/360360
14 : 1171733/360360
15 : 1195757/360360
16 : 2436559/720720
17 : 42142223/12252240
18 : 14274301/4084080
19 : 275295799/77597520
20 : 55835135/15519504
100 : 14466636279520351160221518043104131447711/2788815009188499086581352357412492142272
 
The first harmonic number to exceed the following integers is:
integer = 1 -> n = 2 -> harmonic number = 1.500000 (to 6dp)
integer = 2 -> n = 4 -> harmonic number = 2.083333 (to 6dp)
integer = 3 -> n = 11 -> harmonic number = 3.019877 (to 6dp)
integer = 4 -> n = 31 -> harmonic number = 4.027245 (to 6dp)
integer = 5 -> n = 83 -> harmonic number = 5.002068 (to 6dp)
integer = 6 -> n = 227 -> harmonic number = 6.004367 (to 6dp)
integer = 7 -> n = 616 -> harmonic number = 7.001274 (to 6dp)
integer = 8 -> n = 1674 -> harmonic number = 8.000486 (to 6dp)
integer = 9 -> n = 4550 -> harmonic number = 9.000208 (to 6dp)
integer = 10 -> n = 12367 -> harmonic number = 10.000043 (to 6dp)
 
</pre>
 
=={{header|C++}}==
{{libheader|Boost}}
<langsyntaxhighlight lang="cpp">#include <iomanip>
#include <iostream>
#include <boost/rational.hpp>
Line 140 ⟶ 620:
std::cout << "Position of first term > " << std::setw(2) << n++ << ": " << i << '\n';
}
}</langsyntaxhighlight>
 
{{out}}
Line 178 ⟶ 658:
Position of first term > 9: 4550
Position of first term > 10: 12367
</pre>
 
=={{header|COBOL}}==
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. HARMONIC.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 VARS.
03 N PIC 9(5) VALUE ZERO.
03 HN PIC 9(2)V9(12) VALUE ZERO.
03 INT PIC 99 VALUE ZERO.
01 OUT-VARS.
03 POS PIC Z(4)9.
03 FILLER PIC X(3) VALUE SPACES.
03 H-OUT PIC Z9.9(12).
 
PROCEDURE DIVISION.
BEGIN.
DISPLAY "First 20 harmonic numbers:"
PERFORM SHOW-HARMONIC 20 TIMES.
DISPLAY SPACES.
MOVE ZERO TO N, HN.
DISPLAY "First harmonic number to exceed whole number:"
PERFORM EXCEED-INT 10 TIMES.
STOP RUN.
 
SHOW-HARMONIC.
PERFORM NEXT-HARMONIC.
MOVE HN TO H-OUT.
DISPLAY H-OUT.
 
EXCEED-INT.
ADD 1 TO INT.
PERFORM NEXT-HARMONIC UNTIL HN IS GREATER THAN INT.
MOVE N TO POS.
MOVE HN TO H-OUT.
DISPLAY OUT-VARS.
 
NEXT-HARMONIC.
ADD 1 TO N.
COMPUTE HN = HN + 1 / N.</syntaxhighlight>
{{out}}
<pre>First 20 harmonic numbers:
1.000000000000
1.500000000000
1.833333333333
2.083333333333
2.283333333333
2.449999999999
2.592857142856
2.717857142856
2.828968253967
2.928968253967
3.019877344876
3.103210678209
3.180133755132
3.251562326560
3.318228993226
3.380728993226
3.439552522637
3.495108078192
3.547739657139
3.597739657139
First harmonic number to exceed whole number:
2 1.500000000000
4 2.083333333333
11 3.019877344876
31 4.027245195428
83 5.002068272651
227 6.004366708257
616 7.001274096877
1674 8.000485571261
4550 9.000208060802
12367 10.000043002313</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
 
 
<syntaxhighlight lang="Delphi">
function HarmonicNumber(N: integer): double;
{Calculate sum of }
var I: integer;
begin
Result:=0;
for I:=1 to N do Result:=Result+1/I;
end;
 
 
 
function FirstHarmonicOver(Limit: integer): integer;
{Find first harmonic number over limit}
var HN: double;
begin
for Result:=1 to high(Integer) do
begin
HN:=HarmonicNumber(Result);
if HN>Limit then exit;
end
end;
 
 
procedure ShowHarmonicNumbers(Memo: TMemo);
var I,Inx: integer;
var HN: double;
begin
{Show first 20 harmonic numbers}
for I:=1 to 20 do
begin
HN:=HarmonicNumber(I);
Memo.Lines.Add(Format('%2D: %8.8f',[I,HN]));
end;
{Show the position of the number that exceeds 1..10 }
for I:=1 to 10 do
begin
Inx:=FirstHarmonicOver(I);
Memo.Lines.Add(Format('Position of the first harmonic number > %2D: %4D',[I,Inx]))
end;
end;
 
 
</syntaxhighlight>
{{out}}
<pre>
1: 1.00000000
2: 1.50000000
3: 1.83333333
4: 2.08333333
5: 2.28333333
6: 2.45000000
7: 2.59285714
8: 2.71785714
9: 2.82896825
10: 2.92896825
11: 3.01987734
12: 3.10321068
13: 3.18013376
14: 3.25156233
15: 3.31822899
16: 3.38072899
17: 3.43955252
18: 3.49510808
19: 3.54773966
20: 3.59773966
Position of the first harmonic number > 1: 2
Position of the first harmonic number > 2: 4
Position of the first harmonic number > 3: 11
Position of the first harmonic number > 4: 31
Position of the first harmonic number > 5: 83
Position of the first harmonic number > 6: 227
Position of the first harmonic number > 7: 616
Position of the first harmonic number > 8: 1674
Position of the first harmonic number > 9: 4550
Position of the first harmonic number > 10: 12367
</pre>
 
 
=={{header|EasyLang}}==
{{trans|BASIC256}}
<syntaxhighlight>
numfmt 5 2
print "The first twenty harmonic numbers are:"
for n = 1 to 20
h += 1 / n
print n & " " & h
.
print ""
print "The first harmonic number greater than: "
h = 1
n = 2
for i = 2 to 10
while h < i
h += 1 / n
n += 1
.
print i & " is " & h & ", at position " & n - 1
.
</syntaxhighlight>
{{out}}
<pre>
The first twenty harmonic numbers are:
1 1
2 1.50000
3 1.83333
4 2.08333
5 2.28333
6 2.45000
7 2.59286
8 2.71786
9 2.82897
10 2.92897
11 3.01988
12 3.10321
13 3.18013
14 3.25156
15 3.31823
16 3.38073
17 3.43955
18 3.49511
19 3.54774
20 3.59774
 
The first harmonic number greater than:
2 is 2.08333, at position 4
3 is 3.01988, at position 11
4 is 4.02725, at position 31
5 is 5.00207, at position 83
6 is 6.00437, at position 227
7 is 7.00127, at position 616
8 is 8.00049, at position 1674
9 is 9.00021, at position 4550
10 is 10.00004, at position 12367
</pre>
 
Line 188 ⟶ 883:
 
{{works with|Factor|0.99 2021-02-05}}
<langsyntaxhighlight lang="factor">USING: formatting grouping io kernel lists lists.lazy math
math.functions math.ranges math.statistics math.text.english
prettyprint sequences tools.memory.private ;
Line 211 ⟶ 906:
dup first-gt [ commas ] [ 1 + number>text ] bi
" greater than %2d: %6s (term number %s)\n" printf
] each</langsyntaxhighlight>
{{out}}
<pre>
Line 238 ⟶ 933:
=={{header|Forth}}==
Uses fixed point computation which is more traditional in FORTH.
<syntaxhighlight lang="forth">
<lang Forth>
warnings off
 
Line 268 ⟶ 963:
." The nth index of the first harmonic number that exceeds the nth integer: " cr task2 cr
bye
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 298 ⟶ 993:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">dim as double h = 0.0
dim as uinteger n, i
 
Line 314 ⟶ 1,009:
wend
print "The first harmonic number greater than ";i;" is ";h;", at position ";n-1
next i</langsyntaxhighlight>
{{out}}<pre>The first twenty harmonic numbers are:
1 1
Line 345 ⟶ 1,040:
The first harmonic number greater than 9 is 9.000208062931115, at position 4550
The first harmonic number greater than 10 is 10.00004300827578, at position 12367</pre>
 
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
 
include "NSLog.incl"
 
void local fn BuildHamonics
double h = 0.0
long i, n
NSLog( @"The first twenty harmonic numbers are:\n" )
for i = 1 to 20
h = h + 1.0 / i
NSLog( @"%3d. %.8f", i, h )
next
NSLog( @"\n" )
h = 1 : n = 2
for i = 2 to 10
while h < i
h = h + 1.0 / n
n = n + 1
wend
NSLog( @"The first harmonic number > %2d is %11.8f at position %d.", i, h, n -1 )
next
end fn
 
fn BuildHamonics
 
HandleEvents
</syntaxhighlight>
 
{{output}}
<pre>
The first twenty harmonic numbers are:
 
1. 1.00000000
2. 1.50000000
3. 1.83333333
4. 2.08333333
5. 2.28333333
6. 2.45000000
7. 2.59285714
8. 2.71785714
9. 2.82896825
10. 2.92896825
11. 3.01987734
12. 3.10321068
13. 3.18013376
14. 3.25156233
15. 3.31822899
16. 3.38072899
17. 3.43955252
18. 3.49510808
19. 3.54773966
20. 3.59773966
 
The first harmonic number > 2 is 2.08333333 at position 4.
The first harmonic number > 3 is 3.01987734 at position 11.
The first harmonic number > 4 is 4.02724520 at position 31.
The first harmonic number > 5 is 5.00206827 at position 83.
The first harmonic number > 6 is 6.00436671 at position 227.
The first harmonic number > 7 is 7.00127410 at position 616.
The first harmonic number > 8 is 8.00048557 at position 1674.
The first harmonic number > 9 is 9.00020806 at position 4550.
The first harmonic number > 10 is 10.00004301 at position 12367.
</pre>
 
 
=={{header|Go}}==
{{trans|Wren}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 384 ⟶ 1,149:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 425 ⟶ 1,190:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.List (find)
import Data.Ratio
 
Line 468 ⟶ 1,233:
showRatio =
((<>) . show . numerator)
<*> (('/' :) . show . denominator)</langsyntaxhighlight>
 
{{Out}}
Line 507 ⟶ 1,272:
Term 4550 is the first above 9
Term 12367 is the first above 10</pre>
 
=={{Header|J}}==
To calculate a specific value in the harmonic series, we might define:
<syntaxhighlight lang=J>Hn=: {{ +/ %1+i.y }}"0</syntaxhighlight>
 
Inspecting the first 20 values from Hn, we see:
<syntaxhighlight lang=J> Hn i.4 5
0 1 1.5 1.83333 2.08333
2.28333 2.45 2.59286 2.71786 2.82897
2.92897 3.01988 3.10321 3.18013 3.25156
3.31823 3.38073 3.43955 3.49511 3.54774
</syntaxhighlight>
 
However, this is inefficient -- we're regenerating the sequence each time just to add one more term. So, instead, we should move that <code>i.</code> inside our harmonic series generator:
 
<syntaxhighlight lang=J>Hni=: {{ 0,+/\ %1+i.y}}</syntaxhighlight>
 
Note that we've added an explicit 0 here -- that's both for compatibility with <code>Hn</code> and to ensure that the Hn value at index 1 has the value 1. (We're using a running sum here, which omits the empty case, but that empty case was relevant for us...)
 
Anyways:
<syntaxhighlight lang=J> 4 5$Hni 20
0 1 1.5 1.83333 2.08333
2.28333 2.45 2.59286 2.71786 2.82897
2.92897 3.01988 3.10321 3.18013 3.25156
3.31823 3.38073 3.43955 3.49511 3.54774</syntaxhighlight>
 
Inspecting values from the series, we see that 1e5 terms will get us into numbers larger than 12:
 
<syntaxhighlight lang=J> Hn 1e5
12.0901</syntaxhighlight>
 
So, we can show the index values of the first harmonic numbers which match or exceed integer values:
<syntaxhighlight lang=J> (Hni 1e5) (] ,. I. ,. I. { [) i.13
0 0 0
1 1 1
2 4 2.08333
3 11 3.01988
4 31 4.02725
5 83 5.00207
6 227 6.00437
7 616 7.00127
8 1674 8.00049
9 4550 9.00021
10 12367 10
11 33617 11
12 91380 12</syntaxhighlight>
 
Of course, the later values are not precise integers -- but their fractional part is not significant for J's default display precision:
 
<syntaxhighlight lang=J> (Hn 91380)-12
3.05167e_6</syntaxhighlight>
 
=={{Header|Java}}==
Java does not have a built-in fraction type, so we create our own class Rational.
<syntaxhighlight lang="java">
import java.math.BigInteger;
 
public class HarmonicSeries {
public static void main(String[] aArgs) {
System.out.println("The first twenty Harmonic numbers:");
for ( int i = 1; i <= 20; i++ ) {
System.out.println(String.format("%2s", i) + ": " + harmonicNumber(i));
}
System.out.println();
for ( int i = 1; i <= 10; i++ ) {
System.out.print("The first term greater than ");
System.out.println(String.format("%2s%s%5s", i, " is Term ", indexedHarmonic(i)));
}
 
}
 
private static Rational harmonicNumber(int aNumber) {
Rational result = Rational.ZERO;
for ( int i = 1; i <= aNumber; i++ ) {
result = result.add( new Rational(BigInteger.ONE, BigInteger.valueOf(i)) );
}
return result;
}
private static int indexedHarmonic(int aTarget) {
BigInteger target = BigInteger.valueOf(aTarget);
Rational harmonic = Rational.ZERO;
BigInteger next = BigInteger.ZERO;
while ( harmonic.numerator.compareTo(target.multiply(harmonic.denominator)) <= 0 ) {
next = next.add(BigInteger.ONE);
harmonic = harmonic.add( new Rational(BigInteger.ONE, next) );
}
return next.intValueExact();
}
private static class Rational {
private Rational(BigInteger aNumerator, BigInteger aDenominator) {
numerator = aNumerator;
denominator = aDenominator;
BigInteger gcd = numerator.gcd(denominator);
numerator = numerator.divide(gcd);
denominator = denominator.divide(gcd);
}
@Override
public String toString() {
return numerator + " / " + denominator;
}
private Rational add(Rational aRational) {
BigInteger numer = numerator.multiply(aRational.denominator)
.add(aRational.numerator.multiply(denominator));
BigInteger denom = aRational.denominator.multiply(denominator);
return new Rational(numer, denom);
}
private BigInteger numerator;
private BigInteger denominator;
private static final Rational ZERO = new Rational(BigInteger.ZERO, BigInteger.ONE);
}
 
}
</syntaxhighlight>
{{ out }}
<pre>
The first twenty Harmonic numbers:
1: 1 / 1
2: 3 / 2
3: 11 / 6
4: 25 / 12
5: 137 / 60
6: 49 / 20
7: 363 / 140
8: 761 / 280
9: 7129 / 2520
10: 7381 / 2520
11: 83711 / 27720
12: 86021 / 27720
13: 1145993 / 360360
14: 1171733 / 360360
15: 1195757 / 360360
16: 2436559 / 720720
17: 42142223 / 12252240
18: 14274301 / 4084080
19: 275295799 / 77597520
20: 55835135 / 15519504
 
The first term greater than 1 is Term 2
The first term greater than 2 is Term 4
The first term greater than 3 is Term 11
The first term greater than 4 is Term 31
The first term greater than 5 is Term 83
The first term greater than 6 is Term 227
The first term greater than 7 is Term 616
The first term greater than 8 is Term 1674
The first term greater than 9 is Term 4550
The first term greater than 10 is Term 12367
</pre>
 
=={{header|jq}}==
Line 514 ⟶ 1,443:
This entry requires a rational arithmetic module such as is available
at [[Arithmetic/Rational#jq]].
<langsyntaxhighlight lang="jq"># include "rational"; # a reminder
def harmonic:
Line 543 ⟶ 1,472:
select(.emit).emit) );
 
task1, "", task2(10)</langsyntaxhighlight>
{{out}}
<pre>
Line 582 ⟶ 1,511:
integer = 10 -> n = 12367 -> harmonic number = 10.000043 (to 6dp)
</pre>
 
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">const memoizer = [BigFloat(1.0), BigFloat(1.5)]
 
"""
Line 630 ⟶ 1,558:
 
testharmonics()
</langsyntaxhighlight>{{out}}
<pre>
harmonic(1) = 1.0
Line 672 ⟶ 1,600:
 
=== Using rationals ===
<langsyntaxhighlight lang="julia">const harmonics = accumulate((x, y) -> x + big"1" // y, 1:12370)
 
println("First twenty harmonic numbers as rationals:")
Line 683 ⟶ 1,611:
print("First Harmonic > $n is at position $idx and is: ", harmonics[idx], "\n\n")
end
</langsyntaxhighlight>{{out}}
<pre>
First twenty harmonic numbers as rationals:
Line 729 ⟶ 1,657:
First Harmonic > 10 is at position 12367 and is: 4534503430707033513455566663502488777398404081163864262146240513258488614453237798607335814524420102703735793862177214220961640516162786810577801568379848400841651563172393145644747756934779147852785761076984123029496399397933274328333851023356832490595994957906245622634743917027121730163673444620574773571394586325343348374089752330084853480910846154523214600594885010321970738793199335121376742737688996290912022884023314845989317485564897100378511371007284095835544913458386488350273752793299623280953681770210860670497293958742056567860493303919432966767309289555005524116155997967505009262492686887145801834344158217659625052992919107429112826740068763017007260951761133678087563009777021924759295735860359747992008280482368678698363760290512075843263479257144567423473653608660780306498167138240689075702661825821881383897412095062894498190524562267366610500376186508574923546863369628573748735962288669973834867370052620567124452691818158059495529870775349719430883965813897867964261906884105709015328654134185094852649077443558343796100212309241953109323566593312098467538550988320147927458982568637261872251614826312806756190545537354754639105220779296735305508074404777698608072480025436626465940783557587776095412527179972733639880928504521162532474790119331444432691186539731972229608857034838322577825073128558410147097241778325338487130870125908822766048925435961031468685135925285730005192072367106087421540485758689853548032678218115860840827961919559051579906147674926980159462587970312884204058339415498440724533667854443260894961415867322707773766644126293587970041291934576744798355640180480297466389631305725091134483147261680364583681456904845585042916227359755995566890651618068412417567353169223028238974716410284035466524218357680139996958854138926338447160349489618026519182480829051291094774428369589524841439952414899018430629415759045664629576805779430276126299459472265505596409675499333035181404107887631586541773720233030773460233097013905563454586768052944023799630803277004868637818739278212959623313318901685226624666106128149541383179968968079822908437213133926503243634564555471480742603760558963949447568409555153275556694530840495402464574679819190097934082680991390359677270683921719809487985411431453913318562222280325934810896976109622317012462673397599719705029993095451945802745111845994127113737531302666646673629309399879563721820841693763990040297218084280469660603933736914103580592334169009905536955683757799785465521029810481052093318974648597912401819690931945953441013940611090922220615447632315575131416623986489801748397222861527442923686453815927754305883939843644528744788311441317667800082400625247002131690240576547715553985566084722165603169180546444489624520529458589659642945674302803518493446186365401036652868957343947436300845516052248544996767002703372227801331704347861429376714087429190841582994100706608870432263478840976847125656598528047665054259600221287735441697634905261794158123419440836603187910006400385658161609560077480916666767855249401496376453813742910897685304674607932781480153350592305086143517293124048321908049033338641165570949920967640973467814840149770609739430967880836391708342980969076413706547475361151566568646558729953788076269958878680638806411347398270002468450490060229923546495153668589442405650268354841362770166414940668952342796856334297184594689014220369402540999903691567293267477507617730573216005494288894386265419609930709688051786459868855999927483488595292377625472492052607166011299662062394773003492445503755319504334407628427786801438298993197490802949903537017176795900523366221528304387658556186131452558642788326427005831945047208416461903276903155157668071084197085232239303753932511966601799642086840010635787283417484115163601638040747720429853554897965062666245152120838888282696144547158569268308151508594359471912253952609211269960896327745083608820919865564411609729050094802982153483731969811821363213666501089803250069914862591069398131811421717727581994465281157595132213790173740210606315458787942312889500024592644472634497210343312196800423898410785211559075127039914648882418769844305126070628158439406823975898202123936987508547712323439814808927188496139029784726424065836399799566957465329325900733347158011735890776039622239371179265322102988095792334295987922829904316643744024475158366697011639022690011158534933281478551427221827338035502405739017675964995339845575688974247145430375550691172792583150675040459847494992816879937873922797432917540308251685230808170901253598248750205022912447198383112847277587880630475986296945942943527602129139602849994318853893879911800330577976183782475767979870512555206262710949997353103772493020471652674012338306053325512634115113811440908388247422072755018950413835394298503429471638926223466724120693416489874608276360557167546047009826979490836032462574788898996808959092152232893733971469326230223411125857734727852907092167761679250398986918637504310219629562470003641972668110649513078347115663607119611611006136091187311740932841583114177470218100285066869010543963406829140648421377028252417899384810247910009920738953581331407151723899810868371969278374342093106625781466735739058011357436506412309273928847791977164882301609474829416331188046487042397727216661613196578592821103409588225020153177686173957843637300970946602788598104463189226384477573248319694609//453448392867348851861091842716460781522665326792904183722427862157021725614855278045402902750948524499248477906574954049723047247594567849381505559142259985012563911748565504645288824396149684911357398473040997444532446072249205183698951114867996915790953480940595875198164176514792266197724950029214098402750523319656510658391308781455532640143957171928728555028441113976098936445243888308518334732068287540969911145046182240997844332542069999808052999118116686423274752490237063716145951662497086525502824771022018772683298755747961799756488875473662436395793972289765688786340400767092625088976215404821615642169932407067470102277881619113300360581665503419953488853618786486589079218434762164433122957020446969147378233696729003877954852548129234246125950262402365717815616819562222237997997268259525610560218332639694073974306248739683910746615242978454786299588282966741711638421737040643849869111250119460946958342235754393754105273921365540335675025520532198380359075366480578543033141107171068864236199764731934475297409089137917767464818172280194587098425992699315337227143311157563983501099319586806728853272646048761957836787873218028733894581386787413379357471544256309173104246757027297103897425448969584443551192032578044112779996916037308469908337849261001566062681902158730668479447685029245562145758050351907230317974951652391896463264624212612669169958584934650809482293303230830931776045695753750127961326467827548499522738908622830870349146611375298940888140985679637170914965525299929769378946655485787070387076631251882242836138520842058399796780766046354724533075054753447434289238707943437708102115231865561988793697866081966627386198255657705081440529935972313855299293571946459814547702790931940409505592380201618395383529120246923953942192402976907753500903555076008341911303039471562108255892056978939810785607998919899547795388848467866707335193584754101418435349055093490132220307797847159336930832196642264566173052472986519467903662478761577267524782906438677344301510628707749510764610883151848961955324250103497542040100381108000294328086486819670637824004877822719162400898805753721906246725669673698667303029853553151086095673161642688637369399134211142673038004309271354569340138672196310045673847468188540492497939082450727559160669323441829424345229568861519806871166312840505922345924286612289038405635960847312841549454914894505350287965178933448588642960151653234597627993111784598027362458363048975481887472153211279255977999546404147533745281771529556720982887239728930885170033344102088264480888466142172463254195760915805324061034675182591049442628706041312626422073008073380371673927489824737483560681019534670531017902066234272224653619745905599447903061483059896873406142453228071022111502256443781491460846164401184358168702828324631516293734123540067969597713270070892954605122527765020904360443840604089525630920883767509762055795186065284871898250633904172393012014014535429691316180843284005611214029789777910907448104608381684001408038080004630598753746420393898907687445970436071633844317405361945225336609003279748456376641015025188398108421593478229298294410838458456380669395413849296975844767158362010790056013282230712593275083853985899993525361915338786353135213679507571177474865535450360805151635896650877459021597451290179824388706852573538022338292357056094650723608655495776391045556275691435553166984429143943751883621223890112143444263384709343311021515999913133625576607936737600163990937589076505709728288249796177860701551483858105729270343952736046045949895941189683687455280876075868089128908950093274631325285867675575977007649875882080181911556426324514888965309812114552424769046963560561519998228670210152775853158532301504121266893422531369102008133615525509443494794446512860320064722889237146201868974019228593633572436903033783142941154726917069945760001298893890438043207045074201509279648515350335803482110210899536912444564551795055524051376159340142763939561343534419114897944064189816231618709358147206686123692571007252707031453516920926510941282670271991207431645277787732194166279571541705091430384118591739755560716583929251984774474735360846706097322805037517607175954157003966139895604444104180849566439510557422016972444504568924435928285183045942516523723723922905128092098303510237702313418511361585451364656754043639465582976252775658243115735311521322732866960027744814046142646066362389168699571924976468952738225372771528877335171820809981966462557399840199438944317868064756592423558340956344597149662019813621964301710551795219655353560019310354145741006960293249850509760942103140771516196121166914225789961295123942408454678165630224229246096815718964524008072338418161910957019466321162530778568751489056122708488740001553449809520216651409154456422832210306621326600466249277216434300763703544991709516688672829002850684750220066717750016340009488155733886564204666531055424099636022638066094074880147267683122477920693324135470681030117673286007072403853987896516881673522241375339519109365317259361633140780497503747668264390394453428165247265288377265912593743778917613302228374835985611202269353962434983431127134732498447341566434664481796653135468887881140453881191678527573715771628361883084372307861539269288978542389654945192750390734178119092263987452761982138487929715357003527512352779194620327380792004034424949320206418355200000
</pre>
 
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">-- Task 1
function harmonic (n)
if n < 1 or n ~= math.floor(n) then
error("Argument to harmonic function is not a natural number")
end
local Hn = 1
for i = 2, n do
Hn = Hn + (1/i)
end
return Hn
end
 
-- Task 2
for x = 1, 20 do
print(x .. " :\t" .. harmonic(x))
end
 
-- Task 3
local x, lastInt, Hx = 0, 1
repeat
x = x + 1
Hx = harmonic(x)
if Hx > lastInt then
io.write("The first harmonic number above " .. lastInt)
print(" is " .. Hx .. " at position " .. x)
lastInt = lastInt + 1
end
until lastInt > 10 -- Stretch goal just meant changing that value from 5 to 10
-- Execution still only takes about 120 ms under LuaJIT</syntaxhighlight>
{{out}}
<pre>1 : 1
2 : 1.5
3 : 1.8333333333333
4 : 2.0833333333333
5 : 2.2833333333333
6 : 2.45
7 : 2.5928571428571
8 : 2.7178571428571
9 : 2.8289682539683
10 : 2.9289682539683
11 : 3.0198773448773
12 : 3.1032106782107
13 : 3.1801337551338
14 : 3.2515623265623
15 : 3.318228993229
16 : 3.380728993229
17 : 3.4395525226408
18 : 3.4951080781963
19 : 3.5477396571437
20 : 3.5977396571437
The first harmonic number above 1 is 1.5 at position 2
The first harmonic number above 2 is 2.0833333333333 at position 4
The first harmonic number above 3 is 3.0198773448773 at position 11
The first harmonic number above 4 is 4.0272451954365 at position 31
The first harmonic number above 5 is 5.0020682726802 at position 83
The first harmonic number above 6 is 6.0043667083456 at position 227
The first harmonic number above 7 is 7.0012740971342 at position 616
The first harmonic number above 8 is 8.0004855719958 at position 1674
The first harmonic number above 9 is 9.0002080629311 at position 4550
The first harmonic number above 10 is 10.000043008276 at position 12367</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">nums = HarmonicNumber[Range[15000]];
nums[[;; 20]]
LengthWhile[nums, LessEqualThan[#]] + 1 & /@ Range[10]</langsyntaxhighlight>
{{out}}
<pre>{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}
{2, 4, 11, 31, 83, 227, 616, 1674, 4550, 12367}</pre>
 
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">
harmonic(n):=apply("+",1/makelist(i,i,n))$
 
first_greater_than_n(len):=block(i:1,result:[],while harmonic(i)<=len do (result:endcons(i,result),i:i+1),last(result)+1)$
 
/* Test cases */
/* First 20 harmonic numbers */
makelist(harmonic(j),j,20);
 
/* First harmonic number that exceeds a positive integer from 1 to 5 */
makelist(first_greater_than_n(k),k,5);
</syntaxhighlight>
{{out}}
<pre>
[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]
 
[2,4,11,31,83]
</pre>
 
=={{header|Nim}}==
===Using floats===
<langsyntaxhighlight Nimlang="nim">import strformat
 
iterator h(): (int, float) =
Line 762 ⟶ 1,773:
echo &"Index of the first term greater than {target.int:2}: {idx}"
if target == 10: break
else: target += 1</langsyntaxhighlight>
 
{{out}}
Line 799 ⟶ 1,810:
===Using big integers===
{{libheader|bignum}}
<langsyntaxhighlight Nimlang="nim">import strformat
import bignum
 
Line 821 ⟶ 1,832:
echo &"Index of the first term greater than {target:2}: {idx}"
if target == 10: break
else: inc target</langsyntaxhighlight>
 
{{out}}
Line 855 ⟶ 1,866:
Index of the first term greater than 9: 4550
Index of the first term greater than 10: 12367</pre>
 
=={{header|PARI/GP}}==
<syntaxhighlight lang="parigp">h=0
for(n=1,20,h=h+1/n;print(n," ",h))
h=0; n=1
for(i=1,10,while(h<i,h=h+1/n;n=n+1);print(n-1))</syntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
Line 874 ⟶ 1,891:
for my $i (1..10) {
printf " greater than %2d: %5s\n", $i, firstidx { $_ > $i } @H;
}</langsyntaxhighlight>
{{out}}
<pre>First twenty harmonic numbers as rationals:
Line 896 ⟶ 1,913:
=={{header|Phix}}==
{{libheader|Phix/mpfr}}
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"0.8.4"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
Line 921 ⟶ 1,938:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" greater than %2d: %,6d (%s term)\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">gt</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #7060A8;">ordinal</span><span style="color: #0000FF;">(</span><span style="color: #000000;">gt</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 948 ⟶ 1,965:
 
=== using standard floats ===
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #004080;">integer</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">gn</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">hn</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
Line 972 ⟶ 1,989:
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">wait_key</span><span style="color: #0000FF;">()</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 998 ⟶ 2,015:
=={{header|Prolog}}==
{{works with|SWI Prolog}}
<langsyntaxhighlight lang="prolog">main:-
print_harmonic_series(20),
nl,
Line 1,050 ⟶ 2,067:
nth_harmonic_number(N, T, H1):-
harmonic_next(H1, H2),
nth_harmonic_number(N, T, H2).</langsyntaxhighlight>
 
{{out}}
Line 1,092 ⟶ 2,109:
=={{header|Python}}==
A generator function using fractions:
<langsyntaxhighlight lang="python">from fractions import Fraction
 
def harmonic_series():
Line 1,104 ⟶ 2,121:
from itertools import islice
for n, d in (h.as_integer_ratio() for h in islice(harmonic_series(), 20)):
print(n, '/', d)</langsyntaxhighlight>
 
{{out}}
Line 1,131 ⟶ 2,148:
Or alternatively, in terms of itertools.accumulate:
 
<langsyntaxhighlight lang="python">'''Harmonic series'''
 
from fractions import Fraction
Line 1,205 ⟶ 2,222:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>First 20 terms of the harmonic series:
Line 1,246 ⟶ 2,263:
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ $ "bigrat.qky" loadfile ] now!
0 n->v
Line 1,270 ⟶ 2,287:
again ]
temp release
drop 2drop</langsyntaxhighlight>
 
{{out}}
Line 1,309 ⟶ 2,326:
===Direct Summation===
The talk page helpfully points out that we can be remarkably lazy here.
<langsyntaxhighlight Rlang="rsplus">HofN <- function(n) sum(1/seq_len(n)) #Task 1
H <- sapply(1:100000, HofN)
print(H[1:20]) #Task 2
print(sapply(1:10, function(x) which.max(H > x))) #Task 3 and stretch</langsyntaxhighlight>
{{out}}
<pre>> print(H[1:20]) #Task 2
Line 1,323 ⟶ 2,340:
===Cumulative Sums===
As for doing this properly, R provides a handy cumsum function.
<langsyntaxhighlight Rlang="rsplus">firstNHarmonicNumbers <- function(n) cumsum(1/seq_len(n)) #Task 1
H <- firstNHarmonicNumbers(100000) #Runs stunningly quick
print(H[1:20]) #Task 2
print(sapply(1:10, function(x) which.max(H > x))) #Task 3 and stretch</langsyntaxhighlight>
 
=={{header|Raku}}==
Using [https://modules.raku.org/search/?q=Lingua%3A%3AEN%3A%3ANumbers Lingua::EN::Numbers] from the [https://modules.raku.org/ Raku ecosystem].
<syntaxhighlight lang="raku" perl6line>use Lingua::EN::Numbers;
 
my @H = [\+] (1..*).map: { FatRat.new: 1, $_ };
Line 1,341 ⟶ 2,358:
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;</langsyntaxhighlight>
{{out}}
<pre>First twenty harmonic numbers as rationals:
Line 1,366 ⟶ 2,383:
=={{header|REXX}}==
The default number of decimal digits (9) could've been used instead of &nbsp; '''80''' &nbsp; for this task's particular limits.
<langsyntaxhighlight lang="rexx">/*REXX pgm to calculate N numbers (sums) in the harmonic series and also when they > X. */
parse arg digs sums high ints /*obtain optional arguments from the CL*/
if digs='' | digs="," then digs= 80 /*Not specified? Then use the default.*/
Line 1,399 ⟶ 2,416:
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ?
th: parse arg x; return word('th st nd rd', 1 + (x//10) *(x//100%10\==1) *(x//10<4))</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 1,434 ⟶ 2,451:
12,367th iteration of the harmonic series, the sum is greater than 10
</pre>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
decimals(12)
sum = 0
nNew = 1
limit = 13000
Harmonic = []
 
 
for n = 1 to limit
sum += 1/n
add(Harmonic,[n,sum])
next
 
see "The first twenty harmonic numbers are:" + nl
for n = 1 to 20
see "" + Harmonic[n][1] + " -> " + Harmonic[n][2] + nl
next
see nl
 
for m = 1 to 10
for n = nNew to len(Harmonic)
if Harmonic[n][2] > m
see "The first harmonic number greater than "
see "" + m + " is " + Harmonic[n][2] + ", at position " + n + nl
nNew = n
exit
ok
next
next
</syntaxhighlight>
{{out}}
<pre>
The first twenty harmonic numbers are:
1 -> 1
2 -> 1.500000000000
3 -> 1.833333333333
4 -> 2.083333333333
5 -> 2.283333333333
6 -> 2.450000000000
7 -> 2.592857142857
8 -> 2.717857142857
9 -> 2.828968253968
10 -> 2.928968253968
11 -> 3.019877344877
12 -> 3.103210678211
13 -> 3.180133755134
14 -> 3.251562326562
15 -> 3.318228993229
16 -> 3.380728993229
17 -> 3.439552522641
18 -> 3.495108078196
19 -> 3.547739657144
20 -> 3.597739657144
 
The first harmonic number greater than 1 is 1.500000000000, at position 2
The first harmonic number greater than 2 is 2.083333333333, at position 4
The first harmonic number greater than 3 is 3.019877344877, at position 11
The first harmonic number greater than 4 is 4.027245195437, at position 31
The first harmonic number greater than 5 is 5.002068272680, at position 83
The first harmonic number greater than 6 is 6.004366708346, at position 227
The first harmonic number greater than 7 is 7.001274097134, at position 616
The first harmonic number greater than 8 is 8.000485571996, at position 1674
The first harmonic number greater than 9 is 9.000208062931, at position 4550
The first harmonic number greater than 10 is 10.000043008276, at position 12367
</pre>
 
=={{header|RPL}}==
≪ 0 1 ROT '''FOR''' j INV + '''NEXT''' ≫ ‘'''HARMO'''’ STO
≪ 5 FIX { } 1 20 '''FOR''' n n + '''HARMO NEXT''' ≫ EVAL
{{out}}
<pre>
1: { 1.00000 1.50000 1.83333 2.08333 2.28333 2.45000 2.59286 2.71786 2.82897 2.92897 3.01988 3.10321 3.18013 3.25156 3.31823 3.38073 3.43955 3.49511 3.54774 3.59774 }
</pre>
 
We haved fulfilled the stretched part of the task on a vintage HP-28S, with the objective to be as fast as possible. H(n+1) is calculated directly from H(n), and a <code>FOR..NEXT</code> loop allows to reduce stack depth and eliminate the counter incrementation by the user; 9999 is a magic number used to exit the loop.
≪ → max
≪ { } 0 1 9999 '''FOR''' j
j INV +
'''IF''' OVER SIZE 1 + OVER <
'''THEN''' SWAP j +
'''IF''' DUP SIZE max > '''THEN''' 9999 'j' STO '''END'''
SWAP '''END'''
'''NEXT''' DROP
≫ ≫ ‘'''TASK2'''’ STO
{{out}}
<pre>
1: { 2 4 11 31 83 227 616 1674 4550 12367 }
</pre>
was returned in less than 8 minutes.
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">harmonics = Enumerator.new do |y|
res = 0
(1..).each {|n| y << res += Rational(1, n) }
end
 
n = 20
The first #{n} harmonics (as rationals):""
harmonics.take(n).each_slice(5){|slice| puts "%20s"*slice.size % slice }
 
puts
milestones = (1..10).to_a
harmonics.each.with_index(1) do |h,i|
if h > milestones.first then
puts "The first harmonic number > #{milestones.shift} is #{h.to_f} at position #{i}"
end
break if milestones.empty?
end
</syntaxhighlight>
{{out}}
<pre> 1/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
 
The first harmonic number > 1 is 1.5 at position 2
The first harmonic number > 2 is 2.0833333333333335 at position 4
The first harmonic number > 3 is 3.019877344877345 at position 11
The first harmonic number > 4 is 4.02724519543652 at position 31
The first harmonic number > 5 is 5.002068272680166 at position 83
The first harmonic number > 6 is 6.004366708345566 at position 227
The first harmonic number > 7 is 7.001274097134161 at position 616
The first harmonic number > 8 is 8.00048557199578 at position 1674
The first harmonic number > 9 is 9.00020806293114 at position 4550
The first harmonic number > 10 is 10.000043008275808 at position 12367
</pre>
=={{header|Rust}}==
Using big rationals and big integers from the [https://docs.rs/num/latest/num/ num] crate.
<syntaxhighlight lang="rust">
use num::rational::Ratio;
use num::BigInt;
use std::num::NonZeroU64;
 
fn main() {
for n in 1..=20 {
// `harmonic_number` takes the type `NonZeroU64`,
// which is just a normal u64 which is guaranteed to never be 0.
// We convert n into this type with `n.try_into().unwrap()`,
// where the unwrap is okay because n is never 0.
println!(
"Harmonic number {n} = {}",
harmonic_number(n.try_into().unwrap())
);
}
 
// The unwrap here is likewise okay because 100 is not 0.
println!(
"Harmonic number 100 = {}",
harmonic_number(100.try_into().unwrap())
);
 
// In order to avoid recomputing all the terms in the sum for every harmonic number
// we save the value of the harmonic series between loop iterations
// and just add 1/iter to it.
 
let mut target = 1;
let mut iter = 1;
let mut harmonic_number: Ratio<BigInt> = Ratio::from_integer(1.into());
 
while target <= 10 {
if harmonic_number > Ratio::from_integer(target.into()) {
println!("Position of first term > {target} is {iter}");
target += 1;
}
 
// Compute the next term in the harmonic series.
iter += 1;
harmonic_number += Ratio::from_integer(iter.into()).recip();
}
}
 
fn harmonic_number(n: NonZeroU64) -> Ratio<BigInt> {
// Convert each integer from 1 to n into an arbitrary precision rational number
// and sum their reciprocals.
(1..=n.get())
.map(|i| Ratio::from_integer(i.into()).recip())
.sum()
}
</syntaxhighlight>
 
{{out}}
<pre>
Harmonic number 1 = 1
Harmonic number 2 = 3/2
Harmonic number 3 = 11/6
Harmonic number 4 = 25/12
Harmonic number 5 = 137/60
Harmonic number 6 = 49/20
Harmonic number 7 = 363/140
Harmonic number 8 = 761/280
Harmonic number 9 = 7129/2520
Harmonic number 10 = 7381/2520
Harmonic number 11 = 83711/27720
Harmonic number 12 = 86021/27720
Harmonic number 13 = 1145993/360360
Harmonic number 14 = 1171733/360360
Harmonic number 15 = 1195757/360360
Harmonic number 16 = 2436559/720720
Harmonic number 17 = 42142223/12252240
Harmonic number 18 = 14274301/4084080
Harmonic number 19 = 275295799/77597520
Harmonic number 20 = 55835135/15519504
Harmonic number 100 = 14466636279520351160221518043104131447711/2788815009188499086581352357412492142272
Position of first term > 1 is 2
Position of first term > 2 is 4
Position of first term > 3 is 11
Position of first term > 4 is 31
Position of first term > 5 is 83
Position of first term > 6 is 227
Position of first term > 7 is 616
Position of first term > 8 is 1674
Position of first term > 9 is 4550
Position of first term > 10 is 12367
</pre>
 
=={{header|Tcl}}==
<syntaxhighlight lang="tcl># Task 1
proc harmonic {n} {
if {$n < 1 || $n != [expr {floor($n)}]} {
error "Argument to harmonic function is not a natural number"
}
set Hn 1
for {set i 2} {$i <= $n} {incr i} {
set Hn [expr {$Hn + (1.0/$i)}]
}
return $Hn
}
 
# Task 2
for {set x 1} {$x <= 20} {incr x} {
set Hx [harmonic $x]
puts "$x: $Hx"
}
 
# Task 3 /stretch
set x 0
set lastInt 1
while {$lastInt <= 10} {
incr x
set Hx [harmonic $x]
if {$Hx > $lastInt} {
puts -nonewline "The first harmonic number above $lastInt"
puts " is $Hx at position $x"
incr lastInt
}
}
</syntaxhighlight>
{{out}}
<pre>1: 1
2: 1.5
3: 1.8333333333333333
4: 2.083333333333333
5: 2.283333333333333
6: 2.4499999999999997
7: 2.5928571428571425
8: 2.7178571428571425
9: 2.8289682539682537
10: 2.9289682539682538
11: 3.0198773448773446
12: 3.103210678210678
13: 3.180133755133755
14: 3.251562326562327
15: 3.3182289932289937
16: 3.3807289932289937
17: 3.439552522640758
18: 3.4951080781963135
19: 3.547739657143682
20: 3.597739657143682
The first harmonic number above 1 is 1.5 at position 2
The first harmonic number above 2 is 2.083333333333333 at position 4
The first harmonic number above 3 is 3.0198773448773446 at position 11
The first harmonic number above 4 is 4.02724519543652 at position 31
The first harmonic number above 5 is 5.002068272680166 at position 83
The first harmonic number above 6 is 6.004366708345567 at position 227
The first harmonic number above 7 is 7.001274097134162 at position 616
The first harmonic number above 8 is 8.000485571995782 at position 1674
The first harmonic number above 9 is 9.000208062931115 at position 4550
The first harmonic number above 10 is 10.000043008275778 at position 12367</pre>
 
=={{header|Verilog}}==
<syntaxhighlight lang="verilog">module main;
integer n, i;
real h;
initial begin
h = 0.0;
 
$display("The first twenty harmonic numbers are:");
for(n=1; n<=20; n=n+1) begin
h = h + 1.0 / n;
$display(n, " ", h);
end
$display("");
 
h = 1.0;
n = 2;
for(i=2; i<=10; i=i+1) begin
while (h < i) begin
h = h + 1.0 / n;
n = n + 1;
end
$write("The first harmonic number greater than ");
$display(i, " is ", h, ", at position ", n-1);
end
$finish ;
end
endmodule</syntaxhighlight>
 
=={{header|Wren}}==
{{libheader|Wren-big}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "./big" for BigRat
import "./fmt" for Fmt
 
var harmonic = Fn.new { |n| (1..n).reduce(BigRat.zero) { |sum, i| sum + BigRat.one/i } }
Line 1,462 ⟶ 2,789:
}
n = n + 1
}</langsyntaxhighlight>
 
{{out}}
Line 1,500 ⟶ 2,827:
integer = 9 -> n = 4,550 -> harmonic number = 9.000208 (to 6dp)
integer = 10 -> n = 12,367 -> harmonic number = 10.000043 (to 6dp)
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">func real Harmonic(N); \Return Nth harmonic number
int N; real X;
[X:= 1.0;
while N >= 2 do
[X:= X + 1.0/float(N); N:= N-1];
return X;
];
 
int N, M;
[for N:= 1 to 20 do
[RlOut(0, Harmonic(N));
if rem(N/5) = 0 then CrLf(0);
];
for M:= 1 to 10 do
[N:= 1;
repeat N:= N+1 until Harmonic(N) > float(M);
IntOut(0, M);
Text(0, ": ");
IntOut(0, N);
CrLf(0);
];
]</syntaxhighlight>
 
{{out}}
<pre>
1.00000 1.50000 1.83333 2.08333 2.28333
2.45000 2.59286 2.71786 2.82897 2.92897
3.01988 3.10321 3.18013 3.25156 3.31823
3.38073 3.43955 3.49511 3.54774 3.59774
1: 2
2: 4
3: 11
4: 31
5: 83
6: 227
7: 616
8: 1674
9: 4550
10: 12367
</pre>
55

edits