Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,2 @@
---
from: http://rosettacode.org/wiki/Harmonic_series

View file

@ -0,0 +1,29 @@
In mathematics, the '''n-th''' harmonic number is the sum of the reciprocals of the first '''n''' natural numbers:
<!-- mathml not working
<math xmlns="http://www.w3.org/1998/Math/MathML"><msub><mi>H</mi><mi>n</mi></msub><mo>=</mo><mn>1</mn><mo>+</mo><mfrac><mn>1</mn><mn>2</mn></mfrac><mo>+</mo><mfrac><mn>1</mn><mn>3</mn></mfrac><mo>+</mo><mo>&#x22EF;</mo><mo>+</mo><mfrac><mn>1</mn><mi>n</mi></mfrac><mo>=</mo><munderover><mo>&#x2211;</mo><mrow><mi>k</mi><mo>=</mo><mn>1</mn></mrow><mi>n</mi></munderover><mfrac><mn>1</mn><mi>k</mi></mfrac></math>
-->
<big>'''H<sub>''n''</sub> = 1 + 1/2 + 1/3 + ... + 1/n'''</big>
The series of harmonic numbers thus obtained is often loosely referred to as the harmonic series.
Harmonic numbers are closely related to the [[wp:Riemann_zeta_function|Riemann zeta function]], and roughly approximate the [[wp:Natural_logarithm|natural logarithm function]]; differing by <big>&gamma;</big> (lowercase Gamma), the [[wp:EulerMascheroni_constant|EulerMascheroni 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
;Related
* [[Egyptian fractions]]
<br>

View file

@ -0,0 +1,29 @@
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:
BEGIN
[ 1 : n ]REAL h;
h[ 1 ] := 1;
FOR i FROM 2 TO n DO
h[ i ] := h[ i - 1 ] + ( 1 / i )
OD;
h
END # HARMONIC # ;
# find the first 20 000 harmonic numbers #
[]REAL h = HARMONIC 20 000;
# show the first 20 harmonic numbers #
FOR i TO 20 DO
print( ( whole( i, -2 ), ":", fixed( h[ i ], -14, 8 ), newline ) )
OD;
# find the positions of the first harmonic number > n where n in 1... #
INT rqd int := 1;
REAL rqd real := 1;
FOR i TO UPB h DO
IF h[ i ] > rqd real THEN
# found the first harmonic number greater than rqd real #
print( ( "Position of the first harmonic number > ", whole( rqd int, -2 ), ": ", whole( i, 0 ), newline ) );
rqd int +:= 1;
rqd real +:= 1
FI
OD
END

View file

@ -0,0 +1,21 @@
# 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)
}

View file

@ -0,0 +1,20 @@
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]
]

View file

@ -0,0 +1,18 @@
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

View file

@ -0,0 +1,42 @@
#include <iomanip>
#include <iostream>
#include <boost/rational.hpp>
#include <boost/multiprecision/gmp.hpp>
using integer = boost::multiprecision::mpz_int;
using rational = boost::rational<integer>;
class harmonic_generator {
public:
rational next() {
rational result = term_;
term_ += rational(1, ++n_);
return result;
}
void reset() {
n_ = 1;
term_ = 1;
}
private:
integer n_ = 1;
rational term_ = 1;
};
int main() {
std::cout << "First 20 harmonic numbers:\n";
harmonic_generator hgen;
for (int i = 1; i <= 20; ++i)
std::cout << std::setw(2) << i << ". " << hgen.next() << '\n';
rational h;
for (int i = 1; i <= 80; ++i)
h = hgen.next();
std::cout << "\n100th harmonic number: " << h << "\n\n";
int n = 1;
hgen.reset();
for (int i = 1; n <= 10; ++i) {
if (hgen.next() > n)
std::cout << "Position of first term > " << std::setw(2) << n++ << ": " << i << '\n';
}
}

View file

@ -0,0 +1,39 @@
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.

View file

@ -0,0 +1,17 @@
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

View file

@ -0,0 +1,39 @@
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;

View file

@ -0,0 +1,24 @@
USING: formatting grouping io kernel lists lists.lazy math
math.functions math.ranges math.statistics math.text.english
prettyprint sequences tools.memory.private ;
! Euler-Mascheroni constant
CONSTANT: γ 0.5772156649
: Hn-approx ( n -- ~Hn )
[ log γ + 1 2 ] [ * /f + 1 ] [ sq 12 * /f - ] tri ;
: lharmonics ( -- list ) 1 lfrom [ Hn-approx ] lmap-lazy ;
: first-gt ( m -- n ) lharmonics swap '[ _ < ] lwhile llength ;
"First twenty harmonic numbers as mixed numbers:" print
100 [1,b] [ recip ] map cum-sum
[ 20 head 5 group simple-table. nl ]
[ "One hundredth:" print last . nl ] bi
"(zero based) Index of first value:" print
10 [1,b] [
dup first-gt [ commas ] [ 1 + number>text ] bi
" greater than %2d: %6s (term number %s)\n" printf
] each

View file

@ -0,0 +1,29 @@
warnings off
1.000.000.000.000.000 drop constant 1.0fx \ fractional part is 15 decimal digits.
: .h ( n -- )
s>d <# 14 for # next [char] . hold #s #> type space ;
1.0fx 1 2constant first-harmonic
: round 5 + 10 / ;
: next-harmonic ( h n -- h' n' )
1+ tuck [ 1.0fx 10 * ] literal swap / round + swap ;
: task1
first-harmonic 19 for over cr .h next-harmonic next 2drop ;
: task2
first-harmonic
11 1 do
begin over i 1.0fx * <= while
next-harmonic
repeat
dup .
loop 2drop ;
." The first 10 harmonic numbers: " task1 cr cr
." The nth index of the first harmonic number that exceeds the nth integer: " cr task2 cr
bye

View file

@ -0,0 +1,17 @@
dim as double h = 0.0
dim as uinteger n, i
print "The first twenty harmonic numbers are:"
for n = 1 to 20
h += 1.0/n
print n, h
next n
h = 1 : n = 2
for i=2 to 10
while h<i
h+=1.0/n
n+=1
wend
print "The first harmonic number greater than ";i;" is ";h;", at position ";n-1
next i

View file

@ -0,0 +1,27 @@
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

View file

@ -0,0 +1,23 @@
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

View file

@ -0,0 +1,37 @@
package main
import (
"fmt"
"math/big"
)
func harmonic(n int) *big.Rat {
sum := new(big.Rat)
for i := int64(1); i <= int64(n); i++ {
r := big.NewRat(1, i)
sum.Add(sum, r)
}
return sum
}
func main() {
fmt.Println("The first 20 harmonic numbers and the 100th, expressed in rational form, are:")
numbers := make([]int, 21)
for i := 1; i <= 20; i++ {
numbers[i-1] = i
}
numbers[20] = 100
for _, i := range numbers {
fmt.Printf("%3d : %s\n", i, harmonic(i))
}
fmt.Println("\nThe first harmonic number to exceed the following integers is:")
const limit = 10
for i, n, h := 1, 1, 0.0; i <= limit; n++ {
h += 1.0 / float64(n)
if h > float64(i) {
fmt.Printf("integer = %2d -> n = %6d -> harmonic number = %9.6f (to 6dp)\n", i, n, h)
i++
}
}
}

View file

@ -0,0 +1,44 @@
import Data.List (find)
import Data.Ratio
--------------------- HARMONIC SERIES --------------------
harmonic :: [Rational]
harmonic =
scanl1
(\a x -> a + 1 / x)
[1 ..]
-------------------------- TESTS -------------------------
main :: IO ()
main = do
putStrLn "First 20 terms:"
mapM_ putStrLn $
showRatio <$> take 20 harmonic
putStrLn "\n100th term:"
putStrLn $ showRatio (harmonic !! 99)
putStrLn ""
putStrLn "One-based indices of first terms above threshold values:"
let indexedHarmonic = zip [0 ..] harmonic
mapM_
putStrLn
$ fmap
( showFirstLimit
<*> \n -> find ((> n) . snd) indexedHarmonic
)
[1 .. 10]
-------------------- DISPLAY FORMATTING ------------------
showFirstLimit n (Just (i, r)) =
"Term "
<> show (succ i)
<> " is the first above "
<> show (numerator n)
showRatio :: Ratio Integer -> String
showRatio =
((<>) . show . numerator)
<*> (('/' :) . show . denominator)

View file

@ -0,0 +1 @@
Hn=: {{ +/ %1+i.y }}"0

View file

@ -0,0 +1,5 @@
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

View file

@ -0,0 +1 @@
Hni=: {{ 0,+/\ %1+i.y}}

View file

@ -0,0 +1,5 @@
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

View file

@ -0,0 +1,2 @@
Hn 1e5
12.0901

View file

@ -0,0 +1,14 @@
(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

View file

@ -0,0 +1,2 @@
(Hn 91380)-12
3.05167e_6

View file

@ -0,0 +1,73 @@
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);
}
}

View file

@ -0,0 +1,30 @@
# include "rational"; # a reminder
def harmonic:
reduce range(1; 1+.) as $i ( r(0;1);
radd(.; r(1; $i) ));
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
def task1:
"The first 20 harmonic numbers and the 100th, expressed in rational form, are:",
(range(1;21), 100
| "\(.) : \(harmonic|rpp)" );
def task2($limit):
"The first harmonic number to exceed the following integers is:",
limit($limit;
foreach range(0; infinite) as $n (
{i: 1, n: 1, h: r(0;1)};
.emit = false
| .h = radd(.h; r(1; .n))
| .i as $i
| if .h | rgreaterthan($i)
then .emit = "integer = \(.i|lpad(2)) -> n = \(.n| lpad(6)) -> harmonic number = \(.h|r_to_decimal(6)) (to 6dp)"
| .i += 1
else .
end
| .n += 1;
select(.emit).emit) );
task1, "", task2(10)

View file

@ -0,0 +1,45 @@
const memoizer = [BigFloat(1.0), BigFloat(1.5)]
"""
harmonic(n::Integer)::BigFloat
Calculates harmonic numbers. The integer argument `n` should be positive.
"""
function harmonic(n::Integer)::BigFloat
if n < 0
throw(DomainError(n))
elseif n == 0
return BigFloat(0.0) # by convention
elseif length(memoizer) >= n
return memoizer[n]
elseif length(memoizer) + 1 == n
h = memoizer[end] + BigFloat(1.0) / n
push!(memoizer, h)
return h
elseif n < 1_000_000
start, x = length(memoizer), memoizer[end]
for i in start+1:n
push!(memoizer, (x += big"1.0" / i))
end
return memoizer[end]
else
# use H(n) = eulergamma + digamma(n + 1), instead, if memory use of memoization too large
x = n + big"1.0"
digam = BigFloat()
ccall((:mpfr_digamma, :libmpfr), Int32, (Ref{BigFloat}, Ref{BigFloat}, Int32), digam, x, 1)
return Base.MathConstants.eulergamma + digam
end
end
function testharmonics(upperlimit = 11)
n = 1
while (h = harmonic(n)) < upperlimit
nextintegerfloor = h < 1.8 ? h > 1.0 : floor(h) > floor(memoizer[n - 1])
if n < 21 || nextintegerfloor
println("harmonic($n) = $h")
nextintegerfloor && println(" $n is also the term number for the first harmonic > $(floor(h))")
end
n += 1
end
end
testharmonics()

View file

@ -0,0 +1,11 @@
const harmonics = accumulate((x, y) -> x + big"1" // y, 1:12370)
println("First twenty harmonic numbers as rationals:")
foreach(i -> println(rpad(i, 3), " => ", harmonics[i]), 1:20)
println("\nThe 100th harmonic is: ", harmonics[100], "\n")
for n in 1:10
idx = findfirst(x -> x > n, harmonics)
print("First Harmonic > $n is at position $idx and is: ", harmonics[idx], "\n\n")
end

View file

@ -0,0 +1,29 @@
-- 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

View file

@ -0,0 +1,17 @@
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

View file

@ -0,0 +1,3 @@
nums = HarmonicNumber[Range[15000]];
nums[[;; 20]]
LengthWhile[nums, LessEqualThan[#]] + 1 & /@ Range[10]

View file

@ -0,0 +1,23 @@
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

View file

@ -0,0 +1,23 @@
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

View file

@ -0,0 +1,4 @@
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))

View file

@ -0,0 +1,18 @@
use strict;
use warnings;
use feature 'say';
use Math::AnyNum ':overload';
use List::AllUtils 'firstidx';
my(@H,$n) = 0;
do { ++$n and push @H, $H[-1] + 1/$n } until $H[-1] >= 10;
shift @H;
say 'First twenty harmonic numbers as rationals:';
my $c = 0;
printf("%20s", $_) and (not ++$c%5) and print "\n" for @H[0..19];
say "\nIndex of first value (zero based):";
for my $i (1..10) {
printf " greater than %2d: %5s\n", $i, firstidx { $_ > $i } @H;
}

View file

@ -0,0 +1,26 @@
(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>
<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: #0000FF;">,</span> <span style="color: #000000;">lim</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()=</span><span style="color: #004600;">JS</span><span style="color: #0000FF;">?</span><span style="color: #000000;">8</span><span style="color: #0000FF;">:</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">mpq</span> <span style="color: #000000;">hn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpq_init_set_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">gt</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"First twenty harmonic numbers as rationals:\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">gn</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">lim</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">20</span> <span style="color: #008080;">then</span>
<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;">"%18s%s"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">mpq_get_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">hn</span><span style="color: #0000FF;">),</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)?</span><span style="color: #008000;">" "</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">100</span> <span style="color: #008080;">then</span>
<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;">"\nOne Hundredth:\n%s\n\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">mpq_get_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">hn</span><span style="color: #0000FF;">)})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">mpq_cmp_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">hn</span><span style="color: #0000FF;">,</span><span style="color: #000000;">gn</span><span style="color: #0000FF;">)></span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">gt</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">n</span>
<span style="color: #000000;">gn</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">n</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #7060A8;">mpq_add_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">hn</span><span style="color: #0000FF;">,</span><span style="color: #000000;">hn</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<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;">"(one based) Index of first value:\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">gt</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<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>
<!--

View file

@ -0,0 +1,25 @@
(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>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">gt</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"First twenty harmonic numbers as fractions:\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">gn</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">10</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">20</span> <span style="color: #008080;">then</span>
<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;">"%18.15f%s"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">hn</span><span style="color: #0000FF;">,</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)?</span><span style="color: #008000;">" "</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">100</span> <span style="color: #008080;">then</span>
<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;">"\nOne Hundredth: %18.15f\n\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">hn</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">hn</span><span style="color: #0000FF;">></span><span style="color: #000000;">gn</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">gt</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">n</span>
<span style="color: #000000;">gn</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">n</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #000000;">hn</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">/</span><span style="color: #000000;">n</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<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;">"(one based) Index of first value:\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">gt</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<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>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">wait_key</span><span style="color: #0000FF;">()</span>
<!--

View file

@ -0,0 +1,53 @@
main:-
print_harmonic_series(20),
nl,
nth_harmonic_number(100, T),
Num is numerator(T),
Denom is denominator(T),
writef('100th harmonic number: %t/%t\n', [Num, Denom]),
nl,
print_first_harmonic_greater_than(10).
print_harmonic_series(N):-
writef('First %t harmonic numbers:\n', [N]),
harmonic_first(H),
print_harmonic_series(N, H).
print_harmonic_series(N, H):-
H = h(I, T),
Num is numerator(T),
Denom is denominator(T),
writef('%3r. %t/%t\n', [I, Num, Denom]),
(I == N, ! ; harmonic_next(H, H1), print_harmonic_series(N, H1)).
print_first_harmonic_greater_than(N):-
harmonic_first(H),
print_first_harmonic_greater_than(1, N, H).
print_first_harmonic_greater_than(N, L, _):-
N > L,
!.
print_first_harmonic_greater_than(N, L, H):-
H = h(P, T),
(T > N ->
writef('Position of first term >%3r: %t\n', [N, P]),
N1 is N + 1
;
N1 = N),
harmonic_next(H, H1),
print_first_harmonic_greater_than(N1, L, H1).
harmonic_first(h(1, 1)).
harmonic_next(h(N1, T1), h(N2, T2)):-
N2 is N1 + 1,
T2 is T1 + 1 rdiv N2.
nth_harmonic_number(N, T):-
harmonic_first(H),
nth_harmonic_number(N, T, H).
nth_harmonic_number(N, T, h(N, T)):-!.
nth_harmonic_number(N, T, H1):-
harmonic_next(H1, H2),
nth_harmonic_number(N, T, H2).

View file

@ -0,0 +1,13 @@
from fractions import Fraction
def harmonic_series():
n, h = Fraction(1), Fraction(1)
while True:
yield h
h += 1 / (n + 1)
n += 1
if __name__ == '__main__':
from itertools import islice
for n, d in (h.as_integer_ratio() for h in islice(harmonic_series(), 20)):
print(n, '/', d)

View file

@ -0,0 +1,75 @@
'''Harmonic series'''
from fractions import Fraction
from itertools import accumulate, count, islice
from operator import add
# harmonic :: [Fraction]
def harmonic():
'''Non finite stream of the terms
of the Harmonic series.
'''
return accumulate(
(1 / Fraction(x) for x in count(1)),
add
)
# ------------------------- TEST -------------------------
# main :: IO ()
def main():
'''Tests of the harmonic series function'''
print('First 20 terms of the harmonic series:')
print('\n'.join([
showFraction(nd) for nd in islice(harmonic(), 20)
]))
print('\n100th term:')
print(
showFraction(
next(islice(harmonic(), 99, None))
)
)
print('')
print(
'One-based indices of terms above threshold values:'
)
indexedHarmonic = enumerate(harmonic())
print('\n'.join([
next(
showFirstLimit(n)(x) for x
in indexedHarmonic if n < x[1]
) for n in range(1, 1 + 10)
]))
# ------------------ DISPLAY FORMATTING ------------------
# showFraction :: Fraction -> String
def showFraction(nd):
'''String representation of the fraction nd.
'''
n, d = nd.as_integer_ratio()
return f'{n} / {d}'
# showFirstLimit :: Int -> (Int, Fraction) -> String
def showFirstLimit(n):
'''Report of 1-based index of first term
with a value over n
'''
def go(indexedFraction):
i = indexedFraction[0]
return f'Term {1 + i} is the first above {n}'
return go
# MAIN ---
if __name__ == '__main__':
main()

View file

@ -0,0 +1,18 @@
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

View file

@ -0,0 +1,25 @@
[ $ "bigrat.qky" loadfile ] now!
0 n->v
20 times
[ i^ 1+ n->v 1/v v+
2dup 20 point$ echo$
say " = "
2dup vulgar$ echo$ cr ]
2drop
cr
1 temp put
0 n->v 1
[ dup dip
[ n->v 1/v v+
temp share n->v 2over v< ]
swap if
[ temp share echo
say " : "
dup echo cr
1 temp tally ]
temp share 11 < while
1+
again ]
temp release
drop 2drop

View file

@ -0,0 +1,4 @@
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

View file

@ -0,0 +1,4 @@
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

View file

@ -0,0 +1,34 @@
/*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.*/
if sums='' | sums="," then sums= 20 /* " " " " " " */
if high='' | high="," then high= 10 /* " " " " " " */
if ints='' | ints="," then ints= 1 2 3 4 5 6 7 8 9 10 /*Not specified? " " " */
w= length(sums) + 2 /*width of Nth harmonic index + suffix.*/
numeric digits digs /*have REXX use more numeric dec. digs.*/
s= 0 /*initialize harmonic series sum to 0. */
do j=1 for sums; s= s + 1/j /*calc "sums" of harmonic series nums.*/
@iter= right((j)th(j), w) /*obtain a nicely formatted sum index. */
say right(@iter, w) 'harmonic sum ' s /*indent the output to the terminal. */
end /*j*/
say /*have a blank line between output sets*/
many= words(ints) /*obtain number of limits to be used. */
z= word(ints, 1) /* " the first " " " " */
lastInt= word(ints, many) /* " " last " " " " */
w= length(lastInt) /*W: is the maximum width of any limit*/
#= 1 /*a pointer to a list of integer limits*/
s= 0 /*initialize harmonic series sum to 0. */
do j=1; s= s + 1/j /*calculate sums of harmonic sum index.*/
if s<=z then iterate /*Is sum <= a limit? Then keep going. */
iter= commas(j)th(j) /*obtain a nicely formatted sum index. */
L= length(iter) /*obtain length so as to align output. */
@iter= right(iter, max(L, 25) ) /*indent the output to the terminal. */
say @iter " iteration of the harmonic series, the sum is greater than " right(z, w)
#= # + 1 /*bump the pointer to the next limit. */
if #>many then leave /*Are at the end of the limits? Done. */
z= word(ints, #) /*point to the next limit to be used. */
end /*j*/ /* [↑] above indices are unity─based. */
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
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))

View file

@ -0,0 +1,12 @@
use Lingua::EN::Numbers;
my @H = [\+] (1..*).map: { FatRat.new: 1, $_ };
say "First twenty harmonic numbers as rationals:\n",
@H[^20]».&pretty-rat.batch(5)».fmt("%18s").join: "\n";
put "\nOne Hundredth:\n", pretty-rat @H[99];
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;

View file

@ -0,0 +1,28 @@
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

View file

@ -0,0 +1,17 @@
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

View file

@ -0,0 +1,16 @@
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

View file

@ -0,0 +1,49 @@
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()
}

View file

@ -0,0 +1,19 @@
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

View file

@ -0,0 +1,27 @@
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

View file

@ -0,0 +1,25 @@
import "/big" for BigRat
import "/fmt" for Fmt
var harmonic = Fn.new { |n| (1..n).reduce(BigRat.zero) { |sum, i| sum + BigRat.one/i } }
BigRat.showAsInt = true
System.print("The first 20 harmonic numbers and the 100th, expressed in rational form, are:")
var numbers = (1..20).toList
numbers.add(100)
for (i in numbers) Fmt.print("$3d : $s", i, harmonic.call(i))
System.print("\nThe first harmonic number to exceed the following integers is:")
var i = 1
var limit = 10
var n = 1
var h = 0
while (true) {
h = h + 1/n
if (h > i) {
Fmt.print("integer = $2d -> n = $,6d -> harmonic number = $9.6f (to 6dp)", i, n, h)
i = i + 1
if (i > limit) return
}
n = n + 1
}

View file

@ -0,0 +1,22 @@
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);
];
]

View file

@ -0,0 +1,18 @@
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