Sylvester's sequence: Difference between revisions

From Rosetta Code
Content added Content deleted
m (syntax highlighting fixup automation)
Line 28: Line 28:
{{trans|Nim}}
{{trans|Nim}}


<lang 11l>F sylverster(lim)
<syntaxhighlight lang="11l">F sylverster(lim)
V result = [BigInt(2)]
V result = [BigInt(2)]
L 2..lim
L 2..lim
Line 42: Line 42:
L(item) l
L(item) l
s += 1 / Float(item)
s += 1 / Float(item)
print("\nSum of the reciprocals of the first 10 terms: #.17".format(s))</lang>
print("\nSum of the reciprocals of the first 10 terms: #.17".format(s))</syntaxhighlight>


{{out}}
{{out}}
Line 64: Line 64:
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
Uses Algol 68G's LONG LONG INT and LONG LONG REAL which have specifiable precision. The sum of the reciprocals in the output has been manually edited to replace a large number of nines with ... to reduce the width.
Uses Algol 68G's LONG LONG INT and LONG LONG REAL which have specifiable precision. The sum of the reciprocals in the output has been manually edited to replace a large number of nines with ... to reduce the width.
<lang algol68>BEGIN # calculate elements of Sylvestor's Sequence #
<syntaxhighlight lang="algol68">BEGIN # calculate elements of Sylvestor's Sequence #
PR precision 200 PR # set the number of digits for LONG LONG modes #
PR precision 200 PR # set the number of digits for LONG LONG modes #
# returns an array set to the forst n elements of Sylvestor's Sequence #
# returns an array set to the forst n elements of Sylvestor's Sequence #
Line 90: Line 90:
print( ( "Sum of reciprocals: ", reciprocal sum, newline ) )
print( ( "Sum of reciprocals: ", reciprocal sum, newline ) )
END
END
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 108: Line 108:
=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>sylvester: function [lim][
<syntaxhighlight lang="rebol">sylvester: function [lim][
result: new [2]
result: new [2]
loop 2..lim 'x [
loop 2..lim 'x [
Line 124: Line 124:


print "Sum of the reciprocals of the first 10 items:"
print "Sum of the reciprocals of the first 10 items:"
print sumRep</lang>
print sumRep</syntaxhighlight>


{{out}}
{{out}}
Line 134: Line 134:
1.0</pre>
1.0</pre>
=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK --bignum -f SYLVESTERS_SEQUENCE.AWK
# syntax: GAWK --bignum -f SYLVESTERS_SEQUENCE.AWK
BEGIN {
BEGIN {
Line 147: Line 147:
exit(0)
exit(0)
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 169: Line 169:
{{works with|Chipmunk Basic}}
{{works with|Chipmunk Basic}}
{{trans|FreeBASIC}}
{{trans|FreeBASIC}}
<lang qbasic>
<syntaxhighlight lang="qbasic">
PRINT "10 primeros términos de la sucesión de sylvester:"
PRINT "10 primeros términos de la sucesión de sylvester:"
PRINT
PRINT
Line 187: Line 187:
PRINT "suma de sus recíprocos: "; suma
PRINT "suma de sus recíprocos: "; suma
END
END
</syntaxhighlight>
</lang>




==={{header|FreeBASIC}}===
==={{header|FreeBASIC}}===
'''precisión estándar'''
'''precisión estándar'''
<lang freebasic>
<syntaxhighlight lang="freebasic">
Dim As Double sylvester, suma = 0
Dim As Double sylvester, suma = 0


Line 205: Line 205:
Print !"\nSuma de sus rec¡procos:"; suma
Print !"\nSuma de sus rec¡procos:"; suma
Sleep
Sleep
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 225: Line 225:
==={{header|PureBasic}}===
==={{header|PureBasic}}===
{{trans|FreeBASIC}}
{{trans|FreeBASIC}}
<syntaxhighlight lang="purebasic">
<lang PureBasic>
OpenConsole()
OpenConsole()
PrintN("10 primeros términos de la sucesión de Sylvester:")
PrintN("10 primeros términos de la sucesión de Sylvester:")
Line 244: Line 244:
CloseConsole()
CloseConsole()
End
End
</syntaxhighlight>
</lang>


==={{header|Yabasic}}===
==={{header|Yabasic}}===
{{trans|FreeBASIC}}
{{trans|FreeBASIC}}
<lang yabasic>
<syntaxhighlight lang="yabasic">
print "10 primeros términos de la sucesión de Sylvester:"
print "10 primeros términos de la sucesión de Sylvester:"


Line 260: Line 260:
print "\nSuma de sus rec¡procos: ", suma
print "\nSuma de sus rec¡procos: ", suma
end
end
</syntaxhighlight>
</lang>




=={{header|C++}}==
=={{header|C++}}==
{{libheader|Boost}}
{{libheader|Boost}}
<lang cpp>#include <iomanip>
<syntaxhighlight lang="cpp">#include <iomanip>
#include <iostream>
#include <iostream>
#include <boost/rational.hpp>
#include <boost/rational.hpp>
Line 287: Line 287:
}
}
std::cout << "Sum of reciprocals: " << sum << '\n';
std::cout << "Sum of reciprocals: " << sum << '\n';
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 306: Line 306:


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>
<syntaxhighlight lang="fsharp">
// Sylvester's sequence: Nigel Galloway. June 7th., 2021
// Sylvester's sequence: Nigel Galloway. June 7th., 2021
let S10=Seq.unfold(fun(n,g)->printfn "*%A %A" n g; Some(n,(n*g+1I,n*g) ) )(2I,1I)|>Seq.take 10|>List.ofSeq
let S10=Seq.unfold(fun(n,g)->printfn "*%A %A" n g; Some(n,(n*g+1I,n*g) ) )(2I,1I)|>Seq.take 10|>List.ofSeq
S10|>List.iteri(fun n g->printfn "%2d -> %A" (n+1) g)
S10|>List.iteri(fun n g->printfn "%2d -> %A" (n+1) g)
let n,g=S10|>List.fold(fun(n,g) i->(n*i+g,g*i))(0I,1I) in printfn "\nThe sum of the reciprocals of S10 is \n%A/\n%A" n g
let n,g=S10|>List.fold(fun(n,g) i->(n*i+g,g*i))(0I,1I) in printfn "\nThe sum of the reciprocals of S10 is \n%A/\n%A" n g
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 334: Line 334:


{{works with|Factor|0.99 2021-02-05}}
{{works with|Factor|0.99 2021-02-05}}
<lang factor>USING: io kernel lists lists.lazy math prettyprint ;
<syntaxhighlight lang="factor">USING: io kernel lists lists.lazy math prettyprint ;


: lsylvester ( -- list ) 2 [ dup sq swap - 1 + ] lfrom-by ;
: lsylvester ( -- list ) 2 [ dup sq swap - 1 + ] lfrom-by ;
Line 342: Line 342:


"Sum of the reciprocals of first 10 elements:" print
"Sum of the reciprocals of first 10 elements:" print
0 [ recip + ] foldl .</lang>
0 [ recip + ] foldl .</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 364: Line 364:


=={{header|Fermat}}==
=={{header|Fermat}}==
<lang fermat>Array syl[10];
<syntaxhighlight lang="fermat">Array syl[10];
syl[1]:=2;
syl[1]:=2;
for i=2 to 10 do syl[i]:=1+Prod<n=1,i-1>[syl[n]] od;
for i=2 to 10 do syl[i]:=1+Prod<n=1,i-1>[syl[n]] od;
!![syl];
!![syl];
srec:=Sigma<i=1,10>[1/syl[i]];
srec:=Sigma<i=1,10>[1/syl[i]];
!!srec;</lang>
!!srec;</syntaxhighlight>
{{out}}<pre>
{{out}}<pre>
syl[1] := 2
syl[1] := 2
Line 391: Line 391:
=={{header|Go}}==
=={{header|Go}}==
{{trans|Wren}}
{{trans|Wren}}
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 424: Line 424:
fmt.Println("\nThe sum of their reciprocals as a decimal number (to 211 places) is:")
fmt.Println("\nThe sum of their reciprocals as a decimal number (to 211 places) is:")
fmt.Println(sumRecip.FloatString(211))
fmt.Println(sumRecip.FloatString(211))
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 448: Line 448:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>sylvester :: [Integer]
<syntaxhighlight lang="haskell">sylvester :: [Integer]
sylvester = map s [0 ..]
sylvester = map s [0 ..]
where
where
Line 463: Line 463:


putStr "Sum of reciprocals by fold: "
putStr "Sum of reciprocals by fold: "
print $ foldr ((+) . (1 /) . fromInteger) 0 $ take 10 sylvester</lang>
print $ foldr ((+) . (1 /) . fromInteger) 0 $ take 10 sylvester</syntaxhighlight>
{{out}}
{{out}}
<pre>First 10 elements of Sylvester's sequence:
<pre>First 10 elements of Sylvester's sequence:
Line 481: Line 481:


Simpler way of generating sequence:
Simpler way of generating sequence:
<lang haskell>sylvester :: [Integer]
<syntaxhighlight lang="haskell">sylvester :: [Integer]
sylvester = iterate (\x -> x * (x-1) + 1) 2</lang>
sylvester = iterate (\x -> x * (x-1) + 1) 2</syntaxhighlight>


or applicatively:
or applicatively:


<lang haskell>sylvester :: [Integer]
<syntaxhighlight lang="haskell">sylvester :: [Integer]
sylvester = iterate (succ . ((*) <*> pred)) 2</lang>
sylvester = iterate (succ . ((*) <*> pred)) 2</syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==
<lang jq># Generate the sylvester integers:
<syntaxhighlight lang="jq"># Generate the sylvester integers:
def sylvester:
def sylvester:
foreach range(0; infinite) as $i ({prev: 1, product: 1};
foreach range(0; infinite) as $i ({prev: 1, product: 1};
.product *= .prev
.product *= .prev
| .prev = .product + 1;
| .prev = .product + 1;
.prev);</lang>
.prev);</syntaxhighlight>
Left padding:
Left padding:
<syntaxhighlight lang="jq">
<lang jq>
def lpad($len; $fill): tostring | ($len - length) as $l | ($fill * $l)[:$l] + .;
def lpad($len; $fill): tostring | ($len - length) as $l | ($fill * $l)[:$l] + .;
def lpad($len): lpad($len; " ");
def lpad($len): lpad($len; " ");
def lpad: lpad(4);</lang>
def lpad: lpad(4);</syntaxhighlight>
The task:
The task:
<lang jq>[limit(10; sylvester)]
<syntaxhighlight lang="jq">[limit(10; sylvester)]
| "First 10 Sylvester numbers:",
| "First 10 Sylvester numbers:",
(range(0;10) as $i | "\($i+1|lpad) => \(.[$i])"),
(range(0;10) as $i | "\($i+1|lpad) => \(.[$i])"),
"",
"",
"Sum of reciprocals of first 10 is approximately: \(map( 1/ .) | add)"
"Sum of reciprocals of first 10 is approximately: \(map( 1/ .) | add)"
</syntaxhighlight>
</lang>
{{out}}
{{out}}
For integer precision, we will use `gojq`, the "go" implementation of jq.
For integer precision, we will use `gojq`, the "go" implementation of jq.
Line 525: Line 525:
=={{header|Julia}}==
=={{header|Julia}}==


<lang julia>sylvester(n) = (n == 1) ? big"2" : prod(sylvester, 1:n-1) + big"1"
<syntaxhighlight lang="julia">sylvester(n) = (n == 1) ? big"2" : prod(sylvester, 1:n-1) + big"1"


foreach(n -> println(rpad(n, 3), " => ", sylvester(n)), 1:10)
foreach(n -> println(rpad(n, 3), " => ", sylvester(n)), 1:10)


println("Sum of reciprocals of first 10: ", sum(big"1.0" / sylvester(n) for n in 1:10))
println("Sum of reciprocals of first 10: ", sum(big"1.0" / sylvester(n) for n in 1:10))
</lang>{{out}}
</syntaxhighlight>{{out}}
<pre>
<pre>
1 => 2
1 => 2
Line 547: Line 547:


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>Rest[Nest[Append[#, (Times @@ #) + 1] &, {1}, 10]]
<syntaxhighlight lang="mathematica">Rest[Nest[Append[#, (Times @@ #) + 1] &, {1}, 10]]
N[Total[1/%], 250]</lang>
N[Total[1/%], 250]</syntaxhighlight>
{{out}}
{{out}}
<pre>{2,3,7,43,1807,3263443,10650056950807,113423713055421844361000443,12864938683278671740537145998360961546653259485195807,165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443}
<pre>{2,3,7,43,1807,3263443,10650056950807,113423713055421844361000443,12864938683278671740537145998360961546653259485195807,165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443}
Line 555: Line 555:
=={{header|Nim}}==
=={{header|Nim}}==
{{libheader|bignum}}
{{libheader|bignum}}
<lang Nim>import sequtils
<syntaxhighlight lang="nim">import sequtils
import bignum
import bignum


Line 569: Line 569:
var sum = newRat()
var sum = newRat()
for item in list: sum += newRat(1, item)
for item in list: sum += newRat(1, item)
echo "\nSum of the reciprocals of the first 10 terms: ", sum.toFloat</lang>
echo "\nSum of the reciprocals of the first 10 terms: ", sum.toFloat</syntaxhighlight>


{{out}}
{{out}}
Line 587: Line 587:


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>
<syntaxhighlight lang="parigp">
S=vector(10)
S=vector(10)
S[1]=2
S[1]=2
for(i=2, 10, S[i]=prod(n=1,i-1,S[n])+1)
for(i=2, 10, S[i]=prod(n=1,i-1,S[n])+1)
print(S)
print(S)
print(sum(i=1,10,1/S[i]))</lang>
print(sum(i=1,10,1/S[i]))</syntaxhighlight>
{{out}}<pre>[2, 3, 7, 43, 1807, 3263443, 10650056950807, 113423713055421844361000443, 12864938683278671740537145998360961546653259485195807, 165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443]
{{out}}<pre>[2, 3, 7, 43, 1807, 3263443, 10650056950807, 113423713055421844361000443, 12864938683278671740537145998360961546653259485195807, 165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443]


Line 600: Line 600:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>use strict;
<syntaxhighlight lang="perl">use strict;
use warnings;
use warnings;
use feature 'say';
use feature 'say';
Line 613: Line 613:


say "First 10 elements of Sylvester's sequence: @S";
say "First 10 elements of Sylvester's sequence: @S";
say "\nSum of the reciprocals of first 10 elements: " . float $sum;</lang>
say "\nSum of the reciprocals of first 10 elements: " . float $sum;</syntaxhighlight>
{{out}}
{{out}}
<pre>First 10 elements of Sylvester's sequence: 2 3 7 43 1807 3263443 10650056950807 113423713055421844361000443 12864938683278671740537145998360961546653259485195807 165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443
<pre>First 10 elements of Sylvester's sequence: 2 3 7 43 1807 3263443 10650056950807 113423713055421844361000443 12864938683278671740537145998360961546653259485195807 165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443
Line 621: Line 621:
=={{header|Phix}}==
=={{header|Phix}}==
=== standard precision ===
=== standard precision ===
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #004080;">atom</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">rn</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">rn</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">lim</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">machine_bits</span><span style="color: #0000FF;">()=</span><span style="color: #000000;">32</span><span style="color: #0000FF;">?</span><span style="color: #000000;">53</span><span style="color: #0000FF;">:</span><span style="color: #000000;">64</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">lim</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">machine_bits</span><span style="color: #0000FF;">()=</span><span style="color: #000000;">32</span><span style="color: #0000FF;">?</span><span style="color: #000000;">53</span><span style="color: #0000FF;">:</span><span style="color: #000000;">64</span><span style="color: #0000FF;">))</span>
Line 630: Line 630:
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</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;">"sum of reciprocals: %g\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">rn</span><span style="color: #0000FF;">})</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;">"sum of reciprocals: %g\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">rn</span><span style="color: #0000FF;">})</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 647: Line 647:
=== mpfr version ===
=== mpfr version ===
Note the (minimal) precision settings of 698 and 211 were found by trial and error (ie larger values gain nothing but smaller ones lose accuracy).
Note the (minimal) precision settings of 698 and 211 were found by trial and error (ie larger values gain nothing but smaller ones lose accuracy).
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1.0.0"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (mpfr_set_default_prec[ision] has been renamed)
<span style="color: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1.0.0"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (mpfr_set_default_prec[ision] has been renamed)
Line 667: Line 667:
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</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;">"sum of reciprocals: %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">mpfr_get_fixed</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rn</span><span style="color: #0000FF;">,</span><span style="color: #000000;">211</span><span style="color: #0000FF;">))})</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;">"sum of reciprocals: %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">mpfr_get_fixed</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rn</span><span style="color: #0000FF;">,</span><span style="color: #000000;">211</span><span style="color: #0000FF;">))})</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 687: Line 687:
<br>It doesn't calculate the reciprocal sum as 8080 PL/M has no floating point...
<br>It doesn't calculate the reciprocal sum as 8080 PL/M has no floating point...
<br>This sample can be compiled with the original 8080 PL/M compiler and run under CP/M (or an emulator or clone).
<br>This sample can be compiled with the original 8080 PL/M compiler and run under CP/M (or an emulator or clone).
<lang plm>100H: /* CALCULATE ELEMENTS OF SYLVESTOR'S SEQUENCE */
<syntaxhighlight lang="plm">100H: /* CALCULATE ELEMENTS OF SYLVESTOR'S SEQUENCE */


BDOS: PROCEDURE( FN, ARG ); /* CP/M BDOS SYSTEM CALL */
BDOS: PROCEDURE( FN, ARG ); /* CP/M BDOS SYSTEM CALL */
Line 807: Line 807:
CALL PRINT$LONG$INTEGER( .PRODUCT );
CALL PRINT$LONG$INTEGER( .PRODUCT );
CALL PRINT$NL;
CALL PRINT$NL;
EOF</lang>
EOF</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 824: Line 824:
=={{header|Prolog}}==
=={{header|Prolog}}==
{{works with|SWI Prolog}}
{{works with|SWI Prolog}}
<lang prolog>sylvesters_sequence(N, S, R):-
<syntaxhighlight lang="prolog">sylvesters_sequence(N, S, R):-
sylvesters_sequence(N, S, 2, R, 0).
sylvesters_sequence(N, S, 2, R, 0).


Line 842: Line 842:
N is numerator(Sum),
N is numerator(Sum),
D is denominator(Sum),
D is denominator(Sum),
writef('\nSum of reciprocals: %t / %t\n', [N, D]).</lang>
writef('\nSum of reciprocals: %t / %t\n', [N, D]).</syntaxhighlight>


{{out}}
{{out}}
Line 863: Line 863:
=={{header|Python}}==
=={{header|Python}}==


<lang python>'''Sylvester's sequence'''
<syntaxhighlight lang="python">'''Sylvester's sequence'''


from functools import reduce
from functools import reduce
Line 904: Line 904:
# MAIN ---
# MAIN ---
if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>First 10 terms of OEIS A000058:
<pre>First 10 terms of OEIS A000058:
Line 923: Line 923:


Or as an iteration:
Or as an iteration:
<lang python>'''Sylvester's sequence'''
<syntaxhighlight lang="python">'''Sylvester's sequence'''


from functools import reduce
from functools import reduce
Line 970: Line 970:
# MAIN ---
# MAIN ---
if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>First 10 terms of OEIS A000058:
<pre>First 10 terms of OEIS A000058:
Line 989: Line 989:
=={{header|Quackery}}==
=={{header|Quackery}}==


<lang Quackery>[ $ "bigrat.qky" loadfile ] now!
<syntaxhighlight lang="quackery">[ $ "bigrat.qky" loadfile ] now!


' [ 2 ] 9 times [ dup -1 peek dup 2 ** swap - 1+ join ]
' [ 2 ] 9 times [ dup -1 peek dup 2 ** swap - 1+ join ]
Line 995: Line 995:
dup witheach [ echo cr ] cr
dup witheach [ echo cr ] cr


0 n->v rot witheach [ n->v 1/v v+ ] 222 point$ echo$</lang>
0 n->v rot witheach [ n->v 1/v v+ ] 222 point$ echo$</syntaxhighlight>


{{out}}
{{out}}
Line 1,014: Line 1,014:


=={{header|Raku}}==
=={{header|Raku}}==
<lang perl6>my @S = {1 + [*] @S[^($++)]} … *;
<syntaxhighlight lang="raku" line>my @S = {1 + [*] @S[^($++)]} … *;


put 'First 10 elements of Sylvester\'s sequence: ', @S[^10];
put 'First 10 elements of Sylvester\'s sequence: ', @S[^10];


say "\nSum of the reciprocals of first 10 elements: ", sum @S[^10].map: { FatRat.new: 1, $_ };</lang>
say "\nSum of the reciprocals of first 10 elements: ", sum @S[^10].map: { FatRat.new: 1, $_ };</syntaxhighlight>
{{out}}
{{out}}
<pre>First 10 elements of Sylvester's sequence: 2 3 7 43 1807 3263443 10650056950807 113423713055421844361000443 12864938683278671740537145998360961546653259485195807 165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443
<pre>First 10 elements of Sylvester's sequence: 2 3 7 43 1807 3263443 10650056950807 113423713055421844361000443 12864938683278671740537145998360961546653259485195807 165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443
Line 1,025: Line 1,025:


=={{header|REXX}}==
=={{header|REXX}}==
<lang rexx>/*REXX pgm finds N terms of the Sylvester's sequence & the sum of the their reciprocals.*/
<syntaxhighlight lang="rexx">/*REXX pgm finds N terms of the Sylvester's sequence & the sum of the their reciprocals.*/
parse arg n . /*obtain optional argument from the CL.*/
parse arg n . /*obtain optional argument from the CL.*/
if n=='' | n=="," then n= 10 /*Not specified? Then use the default.*/
if n=='' | n=="," then n= 10 /*Not specified? Then use the default.*/
Line 1,038: Line 1,038:
say /*stick a fork in it, we're all done. */
say /*stick a fork in it, we're all done. */
numeric digits digits() - 1
numeric digits digits() - 1
say 'sum of the first ' n " reciprocals using" digits() 'decimal digits: ' $ / 1</lang>
say 'sum of the first ' n " reciprocals using" digits() 'decimal digits: ' $ / 1</syntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
<pre>
Line 1,056: Line 1,056:


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>def sylvester(n) = (1..n).reduce(2){|a| a*a - a + 1 }
<syntaxhighlight lang="ruby">def sylvester(n) = (1..n).reduce(2){|a| a*a - a + 1 }
(0..9).each {|n| puts "#{n}: #{sylvester n}" }
(0..9).each {|n| puts "#{n}: #{sylvester n}" }
Line 1,062: Line 1,062:
Sum of reciprocals of first 10 terms:
Sum of reciprocals of first 10 terms:
#{(0..9).sum{|n| 1.0r / sylvester(n)}.to_f }"
#{(0..9).sum{|n| 1.0r / sylvester(n)}.to_f }"
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>0: 2
<pre>0: 2
Line 1,079: Line 1,079:
</pre>
</pre>
=={{header|Scheme}}==
=={{header|Scheme}}==
<lang scheme>(define sylvester
<syntaxhighlight lang="scheme">(define sylvester
(lambda (x)
(lambda (x)
(if (= x 1)
(if (= x 1)
Line 1,087: Line 1,087:
(print list)
(print list)
(newline)
(newline)
(print (apply + (map / list)))</lang>
(print (apply + (map / list)))</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,094: Line 1,094:
</pre>
</pre>
=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "bigint.s7i";
include "bigint.s7i";
include "bigrat.s7i";
include "bigrat.s7i";
Line 1,115: Line 1,115:
writeln("\nSum of the reciprocals of the first 10 elements:");
writeln("\nSum of the reciprocals of the first 10 elements:");
writeln(reciprocalSum digits 210);
writeln(reciprocalSum digits 210);
end func;</lang>
end func;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,135: Line 1,135:


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>func sylvester_sequence(n) {
<syntaxhighlight lang="ruby">func sylvester_sequence(n) {
1..n -> reduce({|a| a*(a-1) + 1 }, 2)
1..n -> reduce({|a| a*(a-1) + 1 }, 2)
}
}
Line 1,143: Line 1,143:


say "\nSum of reciprocals of first 10 terms: "
say "\nSum of reciprocals of first 10 terms: "
say 10.of(sylvester_sequence).sum {|n| 1/n }.as_dec(230)</lang>
say 10.of(sylvester_sequence).sum {|n| 1/n }.as_dec(230)</syntaxhighlight>


{{out}}
{{out}}
Line 1,167: Line 1,167:
Using mkrd's BigNumber library.
Using mkrd's BigNumber library.


<lang swift>import BigNumber
<syntaxhighlight lang="swift">import BigNumber


func sylvester(n: Int) -> BInt {
func sylvester(n: Int) -> BInt {
Line 1,187: Line 1,187:
}
}


print("Sum of the reciprocals of first ten in sequence: \(sum)")</lang>
print("Sum of the reciprocals of first ten in sequence: \(sum)")</syntaxhighlight>


{{out}}
{{out}}
Line 1,204: Line 1,204:


=={{header|Verilog}}==
=={{header|Verilog}}==
<syntaxhighlight lang="verilog">
<lang Verilog>
module main;
module main;
integer i;
integer i;
Line 1,228: Line 1,228:
end
end
endmodule
endmodule
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>10 primeros términos de la sucesión de sylvester:
<pre>10 primeros términos de la sucesión de sylvester:
Line 1,248: Line 1,248:
=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|Wren-big}}
{{libheader|Wren-big}}
<lang ecmascript>import "/big" for BigInt, BigRat
<syntaxhighlight lang="ecmascript">import "/big" for BigInt, BigRat


var sylvester = [BigInt.two]
var sylvester = [BigInt.two]
Line 1,267: Line 1,267:
System.print (sumRecip)
System.print (sumRecip)
System.print("\nThe sum of their reciprocals as a decimal number (to 211 places) is:")
System.print("\nThe sum of their reciprocals as a decimal number (to 211 places) is:")
System.print(sumRecip.toDecimal(211))</lang>
System.print(sumRecip.toDecimal(211))</syntaxhighlight>


{{out}}
{{out}}

Revision as of 18:00, 28 August 2022

Task
Sylvester's sequence
You are encouraged to solve this task according to the task description, using any language you may know.
This page uses content from Wikipedia. The original article was at Sylvester's sequence. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)


In number theory, Sylvester's sequence is an integer sequence in which each term of the sequence is the product of the previous terms, plus one.

Its values grow doubly exponentially, and the sum of its reciprocals forms a series of unit fractions that converges to 1 more rapidly than any other series of unit fractions with the same number of terms.

Further, the sum of the first k terms of the infinite series of reciprocals provides the closest possible underestimate of 1 by any k-term Egyptian fraction.


Task
  • Write a routine (function, procedure, generator, whatever) to calculate Sylvester's sequence.
  • Use that routine to show the values of the first 10 elements in the sequence.
  • Show the sum of the reciprocals of the first 10 elements on the sequence, ideally as an exact fraction.


Related tasks


See also


11l

Translation of: Nim
F sylverster(lim)
   V result = [BigInt(2)]
   L 2..lim
      result.append(product(result) + 1)
   R result

V l = sylverster(10)
print(‘First 10 terms of the Sylvester sequence:’)
L(item) l
   print(item)

V s = 0.0
L(item) l
   s += 1 / Float(item)
print("\nSum of the reciprocals of the first 10 terms: #.17".format(s))
Output:
First 10 terms of the Sylvester sequence:
2
3
7
43
1807
3263443
10650056950807
113423713055421844361000443
12864938683278671740537145998360961546653259485195807
165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443

Sum of the reciprocals of the first 10 terms: 0.99999999999999982

ALGOL 68

Works with: ALGOL 68G version Any - tested with release 2.8.3.win32

Uses Algol 68G's LONG LONG INT and LONG LONG REAL which have specifiable precision. The sum of the reciprocals in the output has been manually edited to replace a large number of nines with ... to reduce the width.

BEGIN # calculate elements of Sylvestor's Sequence                         #
    PR precision 200 PR # set the number of digits for LONG LONG modes     #
    # returns an array set to the forst n elements of Sylvestor's Sequence #
    #    starting from 2, the elements are the product of the previous     #
    #                     elements plus 1                                  #
    OP SYLVESTOR = ( INT n )[]LONG LONG INT:
       BEGIN
           [ 1 : n ]LONG LONG INT result;
           LONG LONG INT product := 2;
           result[ 1 ] := 2;
           FOR i FROM 2 TO n DO
               result[ i ] := product + 1;
               product *:= result[ i ]
           OD;
           result
       END;
    # find the first 10 elements of Sylvestor's Seuence #
    []LONG LONG INT seq = SYLVESTOR 10;
    # show the sequence and sum the reciprocals #
    LONG LONG REAL reciprocal sum := 0;
    FOR i FROM LWB seq TO UPB seq DO
        print( ( whole( seq[ i ], 0 ), newline ) );
        reciprocal sum +:= 1 / seq[ i ]
    OD;
    print( ( "Sum of reciprocals: ", reciprocal sum, newline ) )
END
Output:
2
3
7
43
1807
3263443
10650056950807
113423713055421844361000443
12864938683278671740537145998360961546653259485195807
165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443
Sum of reciprocals: +9.99999999999999999999999999999999999999999...999999999999999999999999999964e  -1

Arturo

sylvester: function [lim][
    result: new [2]
    loop 2..lim 'x [
        'result ++ inc fold result .seed:1 [a b][a * b]
    ]
    return result
]
lst: sylvester 10

print "First 10 terms of the Sylvester sequence:"
print lst
print ""

sumRep: round sum map lst => [1 // &]

print "Sum of the reciprocals of the first 10 items:"
print sumRep
Output:
First 10 terms of the Sylvester sequence:
2 3 7 43 1807 3263443 10650056950807 113423713055421844361000443 12864938683278671740537145998360961546653259485195807 165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443 

Sum of the reciprocals of the first 10 items:
1.0

AWK

# syntax: GAWK --bignum -f SYLVESTERS_SEQUENCE.AWK
BEGIN {
    start = 1
    stop = 10
    for (i=start; i<=stop; i++) {
      sylvester = (i == 1) ? 2 : sylvester*sylvester-sylvester+1
      printf("%2d: %d\n",i,sylvester)
      sum += 1 / sylvester
    }
    printf("\nSylvester sequence %d-%d: sum of reciprocals %30.28f\n",start,stop,sum)
    exit(0)
}
Output:
 1: 2
 2: 3
 3: 7
 4: 43
 5: 1807
 6: 3263443
 7: 10650056950807
 8: 113423713055421844361000443
 9: 12864938683278671740537145998360961546653259485195807
10: 165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443

Sylvester sequence 1-10: sum of reciprocals 0.9999999999999998889776975375

BASIC

BASIC256

Works with: True BASIC
Works with: Chipmunk Basic
Translation of: FreeBASIC
PRINT "10 primeros términos de la sucesión de sylvester:"
PRINT

LET suma = 0
FOR i = 1 to 10
    IF i = 1 then
       LET sylvester = 2
    ELSE
       LET sylvester = sylvester*sylvester-sylvester+1
    END IF
    PRINT i; ": "; sylvester
    LET suma = suma + 1 / sylvester
NEXT i

PRINT
PRINT "suma de sus recíprocos: "; suma
END


FreeBASIC

precisión estándar

Dim As Double sylvester, suma = 0

Print "10 primeros t‚rminos de la sucesi¢n de Sylvester:"

For i As Byte = 1 To 10
    sylvester = Iif(i=1, 2, sylvester*sylvester-sylvester+1)
    Print Using "##: &"; i; sylvester
    suma += 1 / sylvester
Next i

Print !"\nSuma de sus rec¡procos:"; suma
Sleep
Output:
10 primeros términos de la sucesión de Sylvester:
 1: 2
 2: 3
 3: 7
 4: 43
 5: 1807
 6: 3263443
 7: 10650056950807
 8: 1.134237130554218E+26
 9: 1.286493868327867E+52
10: 1.6550664732452E+104

Suma de sus recíprocos: 0.9999999999999999

PureBasic

Translation of: FreeBASIC
OpenConsole()
PrintN("10 primeros términos de la sucesión de Sylvester:")

suma.d = 0
For i.i = 1 To 10
  If i = 1 
    sylvester.d = 2 
  Else 
    sylvester.d = sylvester*sylvester-sylvester+1
  EndIf
  PrintN(Str(i) + ": " + StrD(sylvester))
  suma = suma + 1 / sylvester
Next i

Print(#CRLF$ + "Suma de sus recíprocos: " + StrD(suma))
Input()
CloseConsole()
End

Yabasic

Translation of: FreeBASIC
print "10 primeros términos de la sucesión de Sylvester:"

suma = 0
for i = 1 to 10
    if i=1 then sylvester = 2 else sylvester = sylvester*sylvester-sylvester+1 : fi
	print i using("##"), ": ", sylvester
    suma = suma + 1 / sylvester
next i

print "\nSuma de sus rec¡procos: ", suma
end


C++

Library: Boost
#include <iomanip>
#include <iostream>
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>

using integer = boost::multiprecision::cpp_int;
using rational = boost::rational<integer>;

integer sylvester_next(const integer& n) {
    return n * n - n + 1;
}

int main() {
    std::cout << "First 10 elements in Sylvester's sequence:\n";
    integer term = 2;
    rational sum = 0;
    for (int i = 1; i <= 10; ++i) {
        std::cout << std::setw(2) << i << ": " << term << '\n';
        sum += rational(1, term);
        term = sylvester_next(term);
    }
    std::cout << "Sum of reciprocals: " << sum << '\n';
}
Output:
First 10 elements in Sylvester's sequence:
 1: 2
 2: 3
 3: 7
 4: 43
 5: 1807
 6: 3263443
 7: 10650056950807
 8: 113423713055421844361000443
 9: 12864938683278671740537145998360961546653259485195807
10: 165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443
Sum of reciprocals: 27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920805/27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920806

F#

// Sylvester's sequence: Nigel Galloway. June 7th., 2021
let S10=Seq.unfold(fun(n,g)->printfn "*%A %A" n g; Some(n,(n*g+1I,n*g) ) )(2I,1I)|>Seq.take 10|>List.ofSeq
S10|>List.iteri(fun n g->printfn "%2d -> %A" (n+1) g)
let n,g=S10|>List.fold(fun(n,g) i->(n*i+g,g*i))(0I,1I) in printfn "\nThe sum of the reciprocals of S10 is \n%A/\n%A" n g
Output:
 1 -> 2
 2 -> 3
 3 -> 7
 4 -> 43
 5 -> 1807
 6 -> 3263443
 7 -> 10650056950807
 8 -> 113423713055421844361000443
 9 -> 12864938683278671740537145998360961546653259485195807
10 -> 165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443

The sum of the reciprocals of S10 is
27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920805/
27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920806

Factor

Note that if the previous element of the sequence is x, the next element is x2-x+1.

Works with: Factor version 0.99 2021-02-05
USING: io kernel lists lists.lazy math prettyprint ;

: lsylvester ( -- list ) 2 [ dup sq swap - 1 + ] lfrom-by ;

"First 10 elements of Sylvester's sequence:" print
10 lsylvester ltake dup [ . ] leach nl

"Sum of the reciprocals of first 10 elements:" print
0 [ recip + ] foldl .
Output:
First 10 elements of Sylvester's sequence:
2
3
7
43
1807
3263443
10650056950807
113423713055421844361000443
12864938683278671740537145998360961546653259485195807
165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443

Sum of the reciprocals of first 10 elements:
27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920805/27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920806

Or, in other words, the sum is 2739245…3920805/2739245…3920806.

Fermat

Array syl[10];
syl[1]:=2;
for i=2 to 10 do syl[i]:=1+Prod<n=1,i-1>[syl[n]] od;
!![syl];
srec:=Sigma<i=1,10>[1/syl[i]];
!!srec;
Output:

syl[1] := 2
syl[2] := 3
syl[3] := 7
syl[4] := 43
syl[5] := 1807
syl[6] := 3263443
syl[7] := 10650056950807
syl[8] := 113423713055421844361000443
syl[9] := 12864938683278671740537145998360961546653259485195807
syl[10] := 165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443

2739245030860303142341023429167468628119436436758091462794736794160869202622699363433211840458243863492954873728399236975 `
8487974306317730580753883429460344956410077034761330476016739454649828385541500213920805 / 273924503086030314234102342916746 `
862811943643675809146279473679416086920262269936343321184045824386349295487372839923697584879743063177305807538834294603 `
44956410077034761330476016739454649828385541500213920806

Go

Translation of: Wren
package main

import (
    "fmt"
    "math/big"
)

func main() {
    one := big.NewInt(1)
    two := big.NewInt(2)
    next := new(big.Int)
    sylvester := []*big.Int{two}
    prod := new(big.Int).Set(two)
    count := 1
    for count < 10 {
        next.Add(prod, one)
        sylvester = append(sylvester, new(big.Int).Set(next))
        count++
        prod.Mul(prod, next)
    }
    fmt.Println("The first 10 terms in the Sylvester sequence are:")
    for i := 0; i < 10; i++ {
        fmt.Println(sylvester[i])
    }

    sumRecip := new(big.Rat)
    for _, s := range sylvester {
        sumRecip.Add(sumRecip, new(big.Rat).SetFrac(one, s))
    }
    fmt.Println("\nThe sum of their reciprocals as a rational number is:")
    fmt.Println(sumRecip)
    fmt.Println("\nThe sum of their reciprocals as a decimal number (to 211 places) is:")
    fmt.Println(sumRecip.FloatString(211))
}
Output:
The first 10 terms in the Sylvester sequence are:
2
3
7
43
1807
3263443
10650056950807
113423713055421844361000443
12864938683278671740537145998360961546653259485195807
165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443

The sum of their reciprocals as a rational number is:
27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920805/27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920806

The sum of their reciprocals as a decimal number (to 211 places) is:
0.9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999635

Haskell

sylvester :: [Integer]
sylvester = map s [0 ..]
  where
    s 0 = 2
    s n = succ $ foldr ((*) . s) 1 [0 .. pred n]

main :: IO ()
main = do
  putStrLn "First 10 elements of Sylvester's sequence:"
  putStr $ unlines $ map show $ take 10 sylvester

  putStr "\nSum of reciprocals by sum over map: "
  print $ sum $ map ((1 /) . fromInteger) $ take 10 sylvester

  putStr "Sum of reciprocals by fold: "
  print $ foldr ((+) . (1 /) . fromInteger) 0 $ take 10 sylvester
Output:
First 10 elements of Sylvester's sequence:
2
3
7
43
1807
3263443
10650056950807
113423713055421844361000443
12864938683278671740537145998360961546653259485195807
165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443

Sum of reciprocals by sum over map: 0.9999999999999999
Sum of reciprocals by fold: 1.0

Simpler way of generating sequence:

sylvester :: [Integer]
sylvester = iterate (\x -> x * (x-1) + 1) 2

or applicatively:

sylvester :: [Integer]
sylvester = iterate (succ . ((*) <*> pred)) 2

jq

# Generate the sylvester integers:
def sylvester:
  foreach range(0; infinite) as $i ({prev: 1, product: 1};
    .product *= .prev
    | .prev = .product + 1;
    .prev);

Left padding:

def lpad($len; $fill): tostring | ($len - length) as $l | ($fill * $l)[:$l] + .;
def lpad($len): lpad($len; " ");
def lpad: lpad(4);

The task:

[limit(10; sylvester)]
| "First 10 Sylvester numbers:",
  (range(0;10) as $i | "\($i+1|lpad) => \(.[$i])"),
  "",
  "Sum of reciprocals of first 10 is approximately: \(map( 1/ .) | add)"
Output:

For integer precision, we will use `gojq`, the "go" implementation of jq.

First 10 Sylvester numbers:
   1 => 2
   2 => 3
   3 => 7
   4 => 43
   5 => 1807
   6 => 3263443
   7 => 10650056950807
   8 => 113423713055421844361000443
   9 => 12864938683278671740537145998360961546653259485195807
  10 => 165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443

Sum of reciprocals of first 10 is approximately: 0.9999999999999999

Julia

sylvester(n) = (n == 1) ? big"2" : prod(sylvester, 1:n-1) + big"1"

foreach(n -> println(rpad(n, 3), " =>  ", sylvester(n)), 1:10)

println("Sum of reciprocals of first 10: ", sum(big"1.0" / sylvester(n) for n in 1:10))
Output:
1   =>  2
2   =>  3
3   =>  7
4   =>  43
5   =>  1807
6   =>  3263443
7   =>  10650056950807
8   =>  113423713055421844361000443
9   =>  12864938683278671740537145998360961546653259485195807
10  =>  165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443

Sum of reciprocals of first 10: 0.9999999999999999999999999999999999999999999999999999999999999999999999999999914

Mathematica/Wolfram Language

Rest[Nest[Append[#, (Times @@ #) + 1] &, {1}, 10]]
N[Total[1/%], 250]
Output:
{2,3,7,43,1807,3263443,10650056950807,113423713055421844361000443,12864938683278671740537145998360961546653259485195807,165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443}
0.99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999996349359079841301329356159748234615361531272

Nim

Library: bignum
import sequtils
import bignum

proc sylverster(lim: Positive): seq[Int] =
  result.add(newInt(2))
  for _ in 2..lim:
    result.add result.foldl(a * b) + 1

let list = sylverster(10)
echo "First 10 terms of the Sylvester sequence:"
for item in list: echo item

var sum = newRat()
for item in list: sum += newRat(1, item)
echo "\nSum of the reciprocals of the first 10 terms: ", sum.toFloat
Output:
First 10 terms of the Sylvester sequence:
2
3
7
43
1807
3263443
10650056950807
113423713055421844361000443
12864938683278671740537145998360961546653259485195807
165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443

Sum of the reciprocals of the first 10 terms: 0.9999999999999999

PARI/GP

S=vector(10)
S[1]=2
for(i=2, 10, S[i]=prod(n=1,i-1,S[n])+1)
print(S)
print(sum(i=1,10,1/S[i]))
Output:
[2, 3, 7, 43, 1807, 3263443, 10650056950807, 113423713055421844361000443, 12864938683278671740537145998360961546653259485195807, 165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443]

27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920805/27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920806

Perl

use strict;
use warnings;
use feature 'say';
use List::Util 'reduce';
use Math::AnyNum ':overload';
local $Math::AnyNum::PREC = 845;

my(@S,$sum);
push @S, 1 + reduce { $a * $b } @S for 0..10;
shift @S;
$sum += 1/$_ for @S;

say "First 10 elements of Sylvester's sequence: @S";
say "\nSum of the reciprocals of first 10 elements: " . float $sum;
Output:
First 10 elements of Sylvester's sequence: 2 3 7 43 1807 3263443 10650056950807 113423713055421844361000443 12864938683278671740537145998360961546653259485195807 165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443

Sum of the reciprocals of first 10 elements: 0.9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999635

Phix

standard precision

atom n, rn = 0,
     lim = power(2,iff(machine_bits()=32?53:64))
for i=1 to 10 do
    n = iff(i=1?2:n*n-n+1)
    printf(1,iff(n<=lim?"%d: %d\n":"%d: %g\n"),{i,n})
    rn += 1/n
end for
printf(1,"sum of reciprocals: %g\n",{rn})
Output:
1: 2
2: 3
3: 7
4: 43
5: 1807
6: 3263443
7: 10650056950807
8: 1.13424e+26
9: 1.2865e+52
10: 1.65507e+104
sum of reciprocals: 1

mpfr version

Note the (minimal) precision settings of 698 and 211 were found by trial and error (ie larger values gain nothing but smaller ones lose accuracy).

with javascript_semantics
requires("1.0.0") -- (mpfr_set_default_prec[ision] has been renamed)
                  -- (and mpfr_sprintf() replaced with mpfr_get_fixed())
include mpfr.e
mpz n = mpz_init(2), nm1 = mpz_init()
mpfr_set_default_precision(720)
mpfr {rn, tmp} = mpfr_inits(2)
for i=1 to 10 do
    if i>1 then
        mpz_sub_ui(nm1,n,1)
        mpz_mul(n,nm1,n)
        mpz_add_ui(n,n,1)
    end if
    printf(1,"%d: %s\n",{i,mpz_get_str(n)})
    mpfr_set_z(tmp,n)
    mpfr_si_div(tmp,1,tmp)
    mpfr_add(rn,rn,tmp)
end for
printf(1,"sum of reciprocals: %s\n",{shorten(mpfr_get_fixed(rn,211))})
Output:
1: 2
2: 3
3: 7
4: 43
5: 1807
6: 3263443
7: 10650056950807
8: 113423713055421844361000443
9: 12864938683278671740537145998360961546653259485195807
10: 165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443
sum of reciprocals: 0.999999999999999999...99999999999999999635 (213 digits)

PL/M

As the original 8080 PL/M only has unsigned 8 and 16 bit items, this Uses code from the PL/M Long Multiplication sample routines.
It doesn't calculate the reciprocal sum as 8080 PL/M has no floating point...
This sample can be compiled with the original 8080 PL/M compiler and run under CP/M (or an emulator or clone).

100H: /* CALCULATE ELEMENTS OF SYLVESTOR'S SEQUENCE                          */

   BDOS: PROCEDURE( FN, ARG ); /* CP/M BDOS SYSTEM CALL                      */
      DECLARE FN BYTE, ARG ADDRESS;
      GOTO 5;
   END BDOS;
   PRINT$CHAR:   PROCEDURE( C ); DECLARE C BYTE;    CALL BDOS( 2, C ); END;
   PRINT$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
   DECLARE PRINT$NL LITERALLY 'PRINT$STRING( .( 0DH, 0AH, ''$'' ) )';

   DECLARE LONG$INTEGER  LITERALLY '(201)BYTE';
   DECLARE DIGIT$BASE    LITERALLY '10';

   /* PRINTS A LONG INTEGER                                                  */
   PRINT$LONG$INTEGER: PROCEDURE( N$PTR );
      DECLARE N$PTR ADDRESS;
      DECLARE N BASED N$PTR LONG$INTEGER;
      DECLARE ( D, F ) BYTE;
      F = N( 0 );
      DO D = 1 TO N( 0 );
         CALL PRINT$CHAR( N( F ) + '0' );
         F = F - 1;
      END;
   END PRINT$LONG$INTEGER;
   /* IMPLEMENTS LONG MULTIPLICATION, C IS SET TO A * B                      */
   /*     C CAN BE THE SAME LONG$INTEGER AS A OR B                           */
   LONG$MULTIPLY: PROCEDURE( A$PTR, B$PTR, C$PTR );
      DECLARE ( A$PTR, B$PTR, C$PTR ) ADDRESS;
      DECLARE ( A BASED A$PTR, B BASED B$PTR, C BASED C$PTR ) LONG$INTEGER;
      DECLARE MRESULT LONG$INTEGER;
      DECLARE RPOS    BYTE;

      /* MULTIPLIES THE LONG INTEGER IN B BY THE INTEGER A, THE RESULT       */
      /*     IS ADDED TO C, STARTING FROM DIGIT START                        */
      /*     OVERFLOW IS IGNORED                                             */
      MULTIPLY$ELEMENT: PROCEDURE( A, B$PTR, C$PTR, START );
         DECLARE ( B$PTR, C$PTR )                 ADDRESS;
         DECLARE ( A, START )                     BYTE;
         DECLARE ( B BASED B$PTR, C BASED C$PTR ) LONG$INTEGER;
         DECLARE ( CDIGIT, D$CARRY, BPOS, CPOS )  BYTE;
         D$CARRY = 0;
         CPOS    = START;
         DO BPOS = 1 TO B( 0 );
            CDIGIT = C( CPOS ) + ( A * B( BPOS ) ) + D$CARRY;
            IF CDIGIT < DIGIT$BASE THEN D$CARRY = 0;
            ELSE DO;
               /* HAVE DIGITS TO CARRY                                       */
               D$CARRY = CDIGIT  /  DIGIT$BASE;
               CDIGIT  = CDIGIT MOD DIGIT$BASE;
            END;
            C( CPOS ) = CDIGIT;
            CPOS = CPOS + 1;
         END;
         C( CPOS ) = D$CARRY;
         /* REMOVE LEADING ZEROS BUT IF THE NUMBER IS 0, KEEP THE FINAL 0    */
         DO WHILE( CPOS > 1 AND C( CPOS ) = 0 );
            CPOS = CPOS - 1;
         END;
         C( 0 ) = CPOS;
      END MULTIPLY$ELEMENT ;

      /* THE RESULT WILL BE COMPUTED IN MRESULT, ALLOWING A OR B TO BE C     */
      DO RPOS = 1 TO LAST( MRESULT ); MRESULT( RPOS ) = 0; END;
      /* MULTIPLY BY EACH DIGIT AND ADD TO THE RESULT                        */
      DO RPOS = 1 TO A( 0 );
         IF A( RPOS ) <> 0 THEN DO;
            CALL MULTIPLY$ELEMENT( A( RPOS ), B$PTR, .MRESULT, RPOS );
         END;
      END;
      /* RETURN THE RESULT IN C                                              */
      DO RPOS = 0 TO MRESULT( 0 ); C( RPOS ) = MRESULT( RPOS ); END;
   END;
   /* ADDS THE INTEGER A TO THE LONG$INTEGER N                               */
   ADD$BYTE$TO$LONG$INTEGER: PROCEDURE( A, N$PTR );
      DECLARE A BYTE, N$PTR ADDRESS;
      DECLARE N BASED N$PTR LONG$INTEGER;
      DECLARE ( D, D$CARRY, DIGIT ) BYTE;
      D       = 1;
      D$CARRY = A;
      DO WHILE( D$CARRY > 0 );
         DIGIT = N( D ) + D$CARRY;
         IF DIGIT < DIGIT$BASE THEN DO;
            N( D )  = DIGIT;
            D$CARRY = 0;
            END;
         ELSE DO;
             D$CARRY = DIGIT  /  DIGIT$BASE;
             N( D )  = DIGIT MOD DIGIT$BASE;
             D       = D + 1;
             IF D > N( 0 ) THEN DO;
                /* THE NUMBER NOW HAS AN EXTRA DIGIT                         */
                N( 0 )  = D;
                N( D )  = D$CARRY;
                D$CARRY = 0;
             END;
         END;
      END;
   END ADD$BYTE$TO$LONG$INTEGER;
   /* FIND THE FIRST 10 ELEMENTS OF SYLVESTOR'S SEQUENCE                     */
   DECLARE ( SEQ$ELEMENT, PRODUCT ) LONG$INTEGER;
   DECLARE ( I, D )                 BYTE;
   DO D = 2 TO LAST( PRODUCT     ); PRODUCT(     D ) = 0; END;
   DO D = 2 TO LAST( SEQ$ELEMENT ); SEQ$ELEMENT( D ) = 0; END;
   SEQ$ELEMENT( 0 ) = 1; /* THE FIRST SEQUENCE ELEMENT HAS 1 DIGIT...        */
   SEQ$ELEMENT( 1 ) = 2; /* WHICH IS 2                                       */
   PRODUCT(     0 ) = 1;
   PRODUCT(     1 ) = 2;
   CALL PRINT$LONG$INTEGER( .SEQ$ELEMENT );     /* SHOW ELEMENT 1            */
   CALL PRINT$NL;
   DO I = 2 TO 9;
      DO D = 0 TO PRODUCT( 0 ); SEQ$ELEMENT( D ) = PRODUCT( D ); END;
      CALL ADD$BYTE$TO$LONG$INTEGER( 1, .SEQ$ELEMENT );
      CALL PRINT$LONG$INTEGER( .SEQ$ELEMENT );
      CALL LONG$MULTIPLY( .SEQ$ELEMENT, .PRODUCT, .PRODUCT );
      CALL PRINT$NL;
   END;
   /* THE FINAL ELEMENT IS THE PRODUCT PLUS 1                                */
   CALL ADD$BYTE$TO$LONG$INTEGER( 1, .PRODUCT );
   CALL PRINT$LONG$INTEGER( .PRODUCT );
   CALL PRINT$NL;
EOF
Output:
2
3
7
43
1807
3263443
10650056950807
113423713055421844361000443
12864938683278671740537145998360961546653259485195807
165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443

Prolog

Works with: SWI Prolog
sylvesters_sequence(N, S, R):-
    sylvesters_sequence(N, S, 2, R, 0).

sylvesters_sequence(0, [X], X, R, S):-
    !,
    R is S + 1 rdiv X.
sylvesters_sequence(N, [X|Xs], X, R, S):-
    Y is X * X - X + 1,
    M is N - 1,
    T is S + 1 rdiv X,
    sylvesters_sequence(M, Xs, Y, R, T).

main:-
    sylvesters_sequence(9, Sequence, Sum),
    writeln('First 10 elements in Sylvester\'s sequence:'),
    forall(member(S, Sequence), writef('%t\n', [S])),
    N is numerator(Sum),
    D is denominator(Sum),
    writef('\nSum of reciprocals: %t / %t\n', [N, D]).
Output:
First 10 elements in Sylvester's sequence:
2
3
7
43
1807
3263443
10650056950807
113423713055421844361000443
12864938683278671740537145998360961546653259485195807
165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443

Sum of reciprocals: 27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920805 / 27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920806

Python

'''Sylvester's sequence'''

from functools import reduce
from itertools import count, islice


# sylvester :: [Int]
def sylvester():
    '''Non-finite stream of the terms
       of Sylvester's sequence.
       (OEIS A000058)
    '''
    def go(n):
        return 1 + reduce(
            lambda a, x: a * go(x),
            range(0, n),
            1
        ) if 0 != n else 2

    return map(go, count(0))


# ------------------------- TEST -------------------------
# main :: IO ()
def main():
    '''First terms, and sum of reciprocals.'''

    print("First 10 terms of OEIS A000058:")
    xs = list(islice(sylvester(), 10))
    print('\n'.join([
        str(x) for x in xs
    ]))

    print("\nSum of the reciprocals of the first 10 terms:")
    print(
        reduce(lambda a, x: a + 1 / x, xs, 0)
    )


# MAIN ---
if __name__ == '__main__':
    main()
Output:
First 10 terms of OEIS A000058:
2
3
7
43
1807
3263443
10650056950807
113423713055421844361000443
12864938683278671740537145998360961546653259485195807
165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443

Sum of the reciprocals of the first 10 terms:
0.9999999999999999


Or as an iteration:

'''Sylvester's sequence'''

from functools import reduce
from itertools import islice

# sylvester :: [Int]
def sylvester():
    '''A non finite sequence of the terms of OEIS A000058
    '''
    return iterate(
        lambda x: x * (x - 1) + 1
    )(2)


# ------------------------- TEST -------------------------
# main :: IO ()
def main():
    '''First terms, and sum of reciprocals.'''

    print("First 10 terms of OEIS A000058:")
    xs = list(islice(sylvester(), 10))
    print('\n'.join([
        str(x) for x in xs
    ]))

    print("\nSum of the reciprocals of the first 10 terms:")
    print(
        reduce(lambda a, x: a + 1 / x, xs, 0)
    )

# ----------------------- GENERIC ------------------------

# iterate :: (a -> a) -> a -> Gen [a]
def iterate(f):
    '''An infinite list of repeated
       applications of f to x.
    '''
    def go(x):
        v = x
        while True:
            yield v
            v = f(v)
    return go


# MAIN ---
if __name__ == '__main__':
    main()
Output:
First 10 terms of OEIS A000058:
2
3
7
43
1807
3263443
10650056950807
113423713055421844361000443
12864938683278671740537145998360961546653259485195807
165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443

Sum of the reciprocals of the first 10 terms:
0.9999999999999999

Quackery

[ $ "bigrat.qky" loadfile ] now! 

' [ 2 ] 9 times [ dup -1 peek dup 2 ** swap - 1+ join ]

dup witheach [ echo cr ] cr

0 n->v rot witheach [ n->v 1/v v+ ] 222 point$ echo$
Output:

The first 222 digits after the decimal point are shown for the sum of reciprocals.

2
3
7
43
1807
3263443
10650056950807
113423713055421844361000443
12864938683278671740537145998360961546653259485195807
165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443

0.999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999963493590798413

Raku

my @S = {1 + [*] @S[^($++)]} … *;

put 'First 10 elements of Sylvester\'s sequence: ', @S[^10];

say "\nSum of the reciprocals of first 10 elements: ", sum @S[^10].map: { FatRat.new: 1, $_ };
Output:
First 10 elements of Sylvester's sequence: 2 3 7 43 1807 3263443 10650056950807 113423713055421844361000443 12864938683278671740537145998360961546653259485195807 165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443

Sum of the reciprocals of first 10 elements: 0.9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999635

REXX

/*REXX pgm finds N terms of the Sylvester's sequence & the sum of the their reciprocals.*/
parse arg n .                                    /*obtain optional argument from the CL.*/
if n=='' | n==","  then n= 10                    /*Not specified?  Then use the default.*/
numeric digits max(9, 2**(n-7) * 13 + 1)         /*calculate how many dec. digs we need.*/
@.0= 2                                           /*the value of the 1st Sylvester number*/
$= 0
        do j=0  for n;      jm= j - 1            /*calculate the Sylvester sequence.    */
        if j>0  then @.j= @.jm**2 - @.jm + 1     /*calculate  a  Sylvester sequence num.*/
        say 'Sylvester('j") ──► "   @.j          /*display the Sylvester index & number.*/
        $= $   +   1 / @.j                       /*add its reciprocal to the recip. sum.*/
        end   /*j*/
say                                              /*stick a fork in it,  we're all done. */
numeric digits digits() - 1
say 'sum of the first '   n   " reciprocals using"   digits()   'decimal digits: '   $ / 1
output   when using the default inputs:
Sylvester(0) ──►  2
Sylvester(1) ──►  3
Sylvester(2) ──►  7
Sylvester(3) ──►  43
Sylvester(4) ──►  1807
Sylvester(5) ──►  3263443
Sylvester(6) ──►  10650056950807
Sylvester(7) ──►  113423713055421844361000443
Sylvester(8) ──►  12864938683278671740537145998360961546653259485195807
Sylvester(9) ──►  165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443

sum of the first  10  reciprocals using 104 decimal digits:  1

Ruby

def sylvester(n) = (1..n).reduce(2){|a| a*a - a + 1 }
  
(0..9).each {|n| puts "#{n}: #{sylvester n}"  }
puts "
Sum of reciprocals of first 10 terms:
#{(0..9).sum{|n| 1.0r / sylvester(n)}.to_f }"
Output:
0: 2
1: 3
2: 7
3: 43
4: 1807
5: 3263443
6: 10650056950807
7: 113423713055421844361000443
8: 12864938683278671740537145998360961546653259485195807
9: 165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443

Sum of reciprocals of first 10 terms:
1.0

Scheme

(define sylvester
  (lambda (x)
    (if (= x 1)
      2
      (let ((n (sylvester (- x 1)))) (- (* n n) n -1)))))
(define list (map sylvester '(1 2 3 4 5 6 7 8 9 10)))
(print list)
(newline)
(print (apply + (map / list)))
Output:
(2 3 7 43 1807 3263443 10650056950807 113423713055421844361000443 12864938683278671740537145998360961546653259485195807 165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443)
27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920805/27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920806

Seed7

$ include "seed7_05.s7i";
  include "bigint.s7i";
  include "bigrat.s7i";

const func bigInteger: nextSylvester (in bigInteger: prev) is
  return prev * prev - prev + 1_;

const proc: main is func
  local
    var bigInteger: number is 2_;
    var bigRational: reciprocalSum is 0_ / 1_;
    var integer: n is 0;
  begin
    writeln("First 10 elements of Sylvester's sequence:");
    for n range 1 to 10 do
      writeln(number);
      reciprocalSum +:= 1_ / number;
      number := nextSylvester(number);
    end for;
    writeln("\nSum of the reciprocals of the first 10 elements:");
    writeln(reciprocalSum digits 210);
  end func;
Output:
First 10 elements of Sylvester's sequence:
2
3
7
43
1807
3263443
10650056950807
113423713055421844361000443
12864938683278671740537145998360961546653259485195807
165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443

Sum of the reciprocals of the first 10 elements:
0.999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999963

Sidef

func sylvester_sequence(n) {
    1..n -> reduce({|a| a*(a-1) + 1 }, 2)
}

say "First 10 terms in Sylvester's sequence:"
10.of(sylvester_sequence).each_kv{|k,v| '%2s: %s' % (k,v) -> say }

say "\nSum of reciprocals of first 10 terms: "
say 10.of(sylvester_sequence).sum {|n| 1/n }.as_dec(230)
Output:
First 10 terms in Sylvester's sequence:
 0: 2
 1: 3
 2: 7
 3: 43
 4: 1807
 5: 3263443
 6: 10650056950807
 7: 113423713055421844361000443
 8: 12864938683278671740537145998360961546653259485195807
 9: 165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443

Sum of reciprocals of first 10 terms: 
0.99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999996349359079841301329356

Swift

Using mkrd's BigNumber library.

import BigNumber

func sylvester(n: Int) -> BInt {
  var a = BInt(2)

  for _ in 0..<n {
    a = a * a - a + 1
  }

  return a
}

var sum = BDouble(0)

for n in 0..<10 {
  let syl = sylvester(n: n)
  sum += BDouble(1) / BDouble(syl)
  print(syl)
}

print("Sum of the reciprocals of first ten in sequence: \(sum)")
Output:
2
3
7
43
1807
3263443
10650056950807
113423713055421844361000443
12864938683278671740537145998360961546653259485195807
165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443
Sum of the reciprocals of first ten in sequence: 27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920805/27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920806

Verilog

module main;
  integer i;
  real suma, num;

  initial begin
    $display("10 primeros términos de la sucesión de sylvester:");
    $display("");

    suma = 0;
    num = 0;
    for(i=1; i<=10; i=i+1) begin
        if (i==1) num = 2;
        else      num = num * num - num + 1;
    
        $display(i, ": ", num);
        suma = suma + 1 / num;
    end

    $display("");
    $display("suma de sus recíprocos: ", suma);
    $finish ;
  end
endmodule
Output:
10 primeros términos de la sucesión de sylvester:

          1: 2.00000
          2: 3.00000
          3: 7.00000
          4: 43.0000
          5: 1807.00
          6: 3.26344e+06
          7: 1.06501e+13
          8: 1.13424e+26
          9: 1.28649e+52
         10: 1.65507e+104

suma de sus recíprocos: 1.00000


Wren

Library: Wren-big
import "/big" for BigInt, BigRat

var sylvester = [BigInt.two]
var prod = BigInt.two
var count = 1
while (true) {
    var next = prod + 1
    sylvester.add(next)
    count = count + 1
    if (count == 10) break
    prod = prod * next
}
System.print("The first 10 terms in the Sylvester sequence are:")
System.print(sylvester.join("\n"))

var sumRecip = sylvester.reduce(BigRat.zero) { |acc, s| acc + BigRat.new(1, s) }
System.print("\nThe sum of their reciprocals as a rational number is:")
System.print (sumRecip)
System.print("\nThe sum of their reciprocals as a decimal number (to 211 places) is:")
System.print(sumRecip.toDecimal(211))
Output:
The first 10 terms in the Sylvester sequence are:
2
3
7
43
1807
3263443
10650056950807
113423713055421844361000443
12864938683278671740537145998360961546653259485195807
165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443

The sum of their reciprocals as a rational number is:
27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920805/27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920806

The sum of their reciprocals as a decimal number (to 211 places) is:
0.9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999635