Sylvester's sequence: Difference between revisions

Add C# implementation
m (→‎{{header|Haskell}}: Added an applicative variant)
(Add C# implementation)
 
(23 intermediate revisions by 16 users not shown)
Line 1:
{{draft task}}
{{Wikipedia|Sylvester's sequence}}
 
 
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.
 
 
Line 13:
* 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:
:*   [[Egyptian fractions]]
:*   [[Harmonic series]]
 
 
;See also:
:*   [[oeis:A000058|OEIS A000058 - Sylvester's sequence]]
<br><br>
 
=={{header|11l}}==
{{trans|Nim}}
 
<syntaxhighlight lang="11l">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))</syntaxhighlight>
 
{{out}}
<pre>
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
</pre>
 
=={{header|ALGOL 68}}==
{{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.
<langsyntaxhighlight lang="algol68">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 #
Line 54 ⟶ 90:
print( ( "Sum of reciprocals: ", reciprocal sum, newline ) )
END
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 72 ⟶ 108:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">sylvester: function [lim][
result: new [2]
loop 2..lim 'x [
Line 88 ⟶ 124:
 
print "Sum of the reciprocals of the first 10 items:"
print sumRep</langsyntaxhighlight>
 
{{out}}
Line 97 ⟶ 133:
Sum of the reciprocals of the first 10 items:
1.0</pre>
=={{header|AWK}}==
<syntaxhighlight lang="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)
}
</syntaxhighlight>
{{out}}
<pre>
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
</pre>
 
=={{header|BASIC}}==
Line 104 ⟶ 169:
{{works with|Chipmunk Basic}}
{{trans|FreeBASIC}}
<langsyntaxhighlight lang="qbasic">
PRINT "10 primeros términos de la sucesión de sylvester:"
PRINT
Line 122 ⟶ 187:
PRINT "suma de sus recíprocos: "; suma
END
</syntaxhighlight>
</lang>
 
 
==={{header|FreeBASIC}}===
'''precisión estándar'''
<langsyntaxhighlight lang="freebasic">
Dim As Double sylvester, suma = 0
 
Line 140 ⟶ 205:
Print !"\nSuma de sus rec¡procos:"; suma
Sleep
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 160 ⟶ 225:
==={{header|PureBasic}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="purebasic">
<lang PureBasic>
OpenConsole()
PrintN("10 primeros términos de la sucesión de Sylvester:")
Line 179 ⟶ 244:
CloseConsole()
End
</syntaxhighlight>
</lang>
 
==={{header|Yabasic}}===
{{trans|FreeBASIC}}
<langsyntaxhighlight lang="yabasic">
print "10 primeros términos de la sucesión de Sylvester:"
 
Line 195 ⟶ 260:
print "\nSuma de sus rec¡procos: ", suma
end
</syntaxhighlight>
</lang>
 
=={{header|C#}}==
{{trans|Go}}
<syntaxhighlight lang="C#">
using System;
using System.Collections.Generic;
using System.Numerics;
 
public class SylvesterSequence
{
public static void Main(string[] args)
{
BigInteger one = BigInteger.One;
BigInteger two = new BigInteger(2);
List<BigInteger> sylvester = new List<BigInteger> { two };
BigInteger prod = two;
int count = 1;
 
while (count < 10)
{
BigInteger next = BigInteger.Add(prod, one);
sylvester.Add(next);
count++;
prod *= next;
}
 
Console.WriteLine("The first 10 terms in the Sylvester sequence are:");
foreach (var term in sylvester)
{
Console.WriteLine(term);
}
 
// Assuming a BigRational implementation or a workaround for the sum of reciprocals
BigInteger denominator = BigInteger.One;
foreach (var term in sylvester)
{
denominator = BigInteger.Multiply(denominator, term);
}
 
BigInteger numerator = BigInteger.Zero;
foreach (var term in sylvester)
{
numerator += denominator / term;
}
 
// Assuming you have a way to convert this to a decimal representation
Console.WriteLine("\nThe sum of their reciprocals as a rational number is:");
Console.WriteLine($"{numerator}/{denominator}");
 
// For the decimal representation, you might need to perform the division to a fixed number of decimal places
// This is a simplified approach and may not directly achieve 211 decimal places accurately
Console.WriteLine("\nThe sum of their reciprocals as a decimal number (to 211 places) is:");
Console.WriteLine(DecimalDivide(numerator, denominator, 210));
}
 
private static string DecimalDivide(BigInteger numerator, BigInteger denominator, int decimalPlaces)
{
// This is a basic implementation and might not be accurate for very large numbers or very high precision requirements
BigInteger quotient = BigInteger.Divide(numerator * BigInteger.Pow(10, decimalPlaces + 1), denominator);
string quotientStr = quotient.ToString();
string result = quotientStr.Substring(0, quotientStr.Length - decimalPlaces) + "." + quotientStr.Substring(quotientStr.Length - decimalPlaces);
return result;
}
}
</syntaxhighlight>
{{out}}
<pre>
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:
9.999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999634
 
</pre>
 
 
=={{header|C++}}==
{{libheader|Boost}}
<langsyntaxhighlight lang="cpp">#include <iomanip>
#include <iostream>
#include <boost/rational.hpp>
Line 222 ⟶ 373:
}
std::cout << "Sum of reciprocals: " << sum << '\n';
}</langsyntaxhighlight>
 
{{out}}
Line 239 ⟶ 390:
Sum of reciprocals: 27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920805/27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920806
</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
numfmt 8 0
for i = 1 to 10
if i = 1
sylv = 2
else
sylv = sylv * sylv - sylv + 1
.
print sylv
sum += 1 / sylv
.
print ""
print sum
</syntaxhighlight>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
// 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
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 269 ⟶ 436:
 
{{works with|Factor|0.99 2021-02-05}}
<langsyntaxhighlight lang="factor">USING: io kernel lists lists.lazy math prettyprint ;
 
: lsylvester ( -- list ) 2 [ dup sq swap - 1 + ] lfrom-by ;
Line 277 ⟶ 444:
 
"Sum of the reciprocals of first 10 elements:" print
0 [ recip + ] foldl .</langsyntaxhighlight>
{{out}}
<pre>
Line 297 ⟶ 464:
 
Or, in other words, the sum is <code>2739245…392080'''5/'''2739245…392080'''6'''</code>.
 
=={{header|Fermat}}==
<syntaxhighlight lang="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;</syntaxhighlight>
{{out}}<pre>
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
</pre>
 
=={{header|Go}}==
{{trans|Wren}}
<syntaxhighlight lang="go">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))
}</syntaxhighlight>
 
{{out}}
<pre>
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
</pre>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">sylvester :: [Integer]
sylvester = map s [0 ..]
where
Line 314 ⟶ 565:
 
putStr "Sum of reciprocals by fold: "
print $ foldr ((+) . (1 /) . fromInteger) 0 $ take 10 sylvester</langsyntaxhighlight>
{{out}}
<pre>First 10 elements of Sylvester's sequence:
Line 332 ⟶ 583:
 
Simpler way of generating sequence:
<langsyntaxhighlight lang="haskell">sylvester :: [Integer]
sylvester = iterate (\x -> x * (x-1) + 1) 2</langsyntaxhighlight>
 
or applicatively:
 
<langsyntaxhighlight lang="haskell">sylvester :: [Integer]
sylvester = iterate (succ . ((*) <*> pred)) 2</langsyntaxhighlight>
 
=={{header|J}}==
J uses r instead of / to display rationals
 
<syntaxhighlight lang="j"> 2 ('Sum of reciprocals: ' , ":@:(+/))@:%@:([ echo&>)@:((, 1x + */)@[&_~) 9
2
3
7
43
1807
3263443
10650056950807
113423713055421844361000443
12864938683278671740537145998360961546653259485195807
165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443
Sum of reciprocals: 27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920805r27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920806</syntaxhighlight>
 
=={{header|jq}}==
<langsyntaxhighlight lang="jq"># Generate the sylvester integers:
def sylvester:
foreach range(0; infinite) as $i ({prev: 1, product: 1};
.product *= .prev
| .prev = .product + 1;
.prev);</langsyntaxhighlight>
Left padding:
<syntaxhighlight lang="jq">
<lang jq>
def lpad($len; $fill): tostring | ($len - length) as $l | ($fill * $l)[:$l] + .;
def lpad($len): lpad($len; " ");
def lpad: lpad(4);</langsyntaxhighlight>
The task:
<langsyntaxhighlight lang="jq">[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)"
</syntaxhighlight>
</lang>
{{out}}
For integer precision, we will use `gojq`, the "go" implementation of jq.
Line 376 ⟶ 643:
=={{header|Julia}}==
 
<langsyntaxhighlight 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)
 
println("Sum of reciprocals of first 10: ", sum(big"1.0" / sylvester(n) for n in 1:10))
</langsyntaxhighlight>{{out}}
<pre>
1 => 2
Line 395 ⟶ 662:
 
Sum of reciprocals of first 10: 0.9999999999999999999999999999999999999999999999999999999999999999999999999999914
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">Rest[Nest[Append[#, (Times @@ #) + 1] &, {1}, 10]]
N[Total[1/%], 250]</syntaxhighlight>
{{out}}
<pre>{2,3,7,43,1807,3263443,10650056950807,113423713055421844361000443,12864938683278671740537145998360961546653259485195807,165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443}
0.99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999996349359079841301329356159748234615361531272</pre>
 
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">
sylvester[n]:= if n=0 then sylvester[n]:2 else sylvester[n-1]^2-sylvester[n-1]+1$
 
/* Test cases */
makelist(sylvester[i],i,0,9);
 
apply("+",1/%);
</syntaxhighlight>
{{out}}
<pre>
[2,3,7,43,1807,3263443,10650056950807,113423713055421844361000443,12864938683278671740537145998360961546653259485195807,165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443]
 
27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920805/27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920806
</pre>
 
=={{header|Nim}}==
{{libheader|bignum}}
<langsyntaxhighlight Nimlang="nim">import sequtils
import bignum
 
Line 413 ⟶ 703:
var sum = newRat()
for item in list: sum += newRat(1, item)
echo "\nSum of the reciprocals of the first 10 terms: ", sum.toFloat</langsyntaxhighlight>
 
{{out}}
Line 429 ⟶ 719:
 
Sum of the reciprocals of the first 10 terms: 0.9999999999999999</pre>
 
=={{header|PARI/GP}}==
<syntaxhighlight lang="parigp">
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]))</syntaxhighlight>
{{out}}<pre>[2, 3, 7, 43, 1807, 3263443, 10650056950807, 113423713055421844361000443, 12864938683278671740537145998360961546653259485195807, 165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443]
 
27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920805/27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920806
 
</pre>
 
=={{header|Pascal}}==
{{works with|Free Pascal}}
Free Pascal console program, using the library IntXLib4Pascal for arbitrarily large integers. I couldn't get the library to work with Delphi 7; it's said to work with Delphi 2010 and above.
<syntaxhighlight lang="pascal">
program SylvesterSeq;
 
{$mode objfpc}{$H+}
 
uses SysUtils,
UIntX; // in the library IntX4Pascal
(*
As noted in the Wikipedia article "Sylvester's sequence", we have
1/2 + 1/3 + ... + 1/s[j-1] = (s[j] - 2)/(s[j] - 1),
so that instead of summing the reciprocals explicitly we can just
calculate an extra term.
*)
var
s : UIntX.TIntX; // arbitrarily large integer
i : integer;
begin
s := 1;
for i := 0 to 9 do begin
inc(s);
WriteLn( SysUtils.Format( 's[%d] = %s', [i, s.ToString]));
s := s*(s - 1);
end;
WriteLn( 'Sum of reciprocals =');
WriteLn( (s - 1).ToString);
WriteLn( '/'); // on a separate line for clarity
WriteLn( s.ToString);
end.
</syntaxhighlight>
{{out}}
<pre>
s[0] = 2
s[1] = 3
s[2] = 7
s[3] = 43
s[4] = 1807
s[5] = 3263443
s[6] = 10650056950807
s[7] = 113423713055421844361000443
s[8] = 12864938683278671740537145998360961546653259485195807
s[9] = 1655066473245199641984681954444391800175131527063774978418513887665358686
39572406808911988131737645185443
Sum of reciprocals =
27392450308603031423410234291674686281194364367580914627947367941608692026226993
63433211840458243863492954873728399236975848797430631773058075388342946034495641
0077034761330476016739454649828385541500213920805
/
27392450308603031423410234291674686281194364367580914627947367941608692026226993
63433211840458243863492954873728399236975848797430631773058075388342946034495641
0077034761330476016739454649828385541500213920806
</pre>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
Line 444 ⟶ 802:
 
say "First 10 elements of Sylvester's sequence: @S";
say "\nSum of the reciprocals of first 10 elements: " . float $sum;</langsyntaxhighlight>
{{out}}
<pre>First 10 elements of Sylvester's sequence: 2 3 7 43 1807 3263443 10650056950807 113423713055421844361000443 12864938683278671740537145998360961546653259485195807 165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443
Line 452 ⟶ 810:
=={{header|Phix}}==
=== standard precision ===
<!--<langsyntaxhighlight Phixlang="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: #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 461 ⟶ 819:
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 478 ⟶ 836:
=== 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).
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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)
Line 498 ⟶ 856:
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 518 ⟶ 876:
<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).
<langsyntaxhighlight lang="plm">100H: /* CALCULATE ELEMENTS OF SYLVESTOR'S SEQUENCE */
 
BDOS: PROCEDURE( FN, ARG ); /* CP/M BDOS SYSTEM CALL */
Line 638 ⟶ 996:
CALL PRINT$LONG$INTEGER( .PRODUCT );
CALL PRINT$NL;
EOF</langsyntaxhighlight>
{{out}}
<pre>
Line 655 ⟶ 1,013:
=={{header|Prolog}}==
{{works with|SWI Prolog}}
<langsyntaxhighlight lang="prolog">sylvesters_sequence(N, S, R):-
sylvesters_sequence(N, S, 2, R, 0).
 
Line 673 ⟶ 1,031:
N is numerator(Sum),
D is denominator(Sum),
writef('\nSum of reciprocals: %t / %t\n', [N, D]).</langsyntaxhighlight>
 
{{out}}
Line 694 ⟶ 1,052:
=={{header|Python}}==
 
<langsyntaxhighlight lang="python">'''Sylvester's sequence'''
 
from functools import reduce
Line 735 ⟶ 1,093:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>First 10 terms of OEIS A000058:
Line 751 ⟶ 1,109:
Sum of the reciprocals of the first 10 terms:
0.9999999999999999</pre>
 
 
Or as an iteration:
<syntaxhighlight lang="python">'''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()</syntaxhighlight>
{{Out}}
<pre>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</pre>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="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$</syntaxhighlight>
 
{{out}}
The first 222 digits after the decimal point are shown for the sum of reciprocals.
<pre>2
3
7
43
1807
3263443
10650056950807
113423713055421844361000443
12864938683278671740537145998360961546653259485195807
165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443
 
0.999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999963493590798413
</pre>
 
=={{header|Raku}}==
<syntaxhighlight lang="raku" perl6line>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, $_ };</langsyntaxhighlight>
{{out}}
<pre>First 10 elements of Sylvester's sequence: 2 3 7 43 1807 3263443 10650056950807 113423713055421844361000443 12864938683278671740537145998360961546653259485195807 165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443
Line 764 ⟶ 1,214:
 
=={{header|REXX}}==
<langsyntaxhighlight 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.*/
if n=='' | n=="," then n= 10 /*Not specified? Then use the default.*/
Line 777 ⟶ 1,227:
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</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 794 ⟶ 1,244:
</pre>
 
=={{header|RPL}}==
{{works with|HP|49}}
≪ { 2 3 }
'''DO'''
DUP ΠLIST 1 + +
'''UNTIL''' DUP2 SIZE == '''END'''
NIP
≫ '<span style="color:blue">SYLV</span>' STO
 
10 <span style="color:blue">SYLV</span>
DUP INV ∑LIST EXPAND
{{out}}
<pre>
2: { 2 3 7 43 1807 3263443 10650056950807 113423713055421844361000443 12864938683278671740537145998360961546653259485195807 165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443 }
1: 27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920805 /
27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920806
</pre>
 
=={{header|Ruby}}==
<syntaxhighlight lang="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 }"
</syntaxhighlight>
{{out}}
<pre>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
</pre>
 
=={{header|Scheme}}==
<syntaxhighlight lang="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)))</syntaxhighlight>
{{out}}
<pre>
(2 3 7 43 1807 3263443 10650056950807 113423713055421844361000443 12864938683278671740537145998360961546653259485195807 165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443)
27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920805/27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920806
</pre>
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "bigint.s7i";
include "bigrat.s7i";
Line 816 ⟶ 1,323:
writeln("\nSum of the reciprocals of the first 10 elements:");
writeln(reciprocalSum digits 210);
end func;</langsyntaxhighlight>
{{out}}
<pre>
Line 836 ⟶ 1,343:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func sylvester_sequence(n) {
1..n -> reduce({|a| a*(a-1) + 1 }, 2)
}
Line 844 ⟶ 1,351:
 
say "\nSum of reciprocals of first 10 terms: "
say 10.of(sylvester_sequence).sum {|n| 1/n }.as_dec(230)</langsyntaxhighlight>
 
{{out}}
Line 864 ⟶ 1,371:
</pre>
 
=={{header|Swift}}==
 
Using mkrd's BigNumber library.
 
<syntaxhighlight lang="swift">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)")</syntaxhighlight>
 
{{out}}
 
<pre>2
3
7
43
1807
3263443
10650056950807
113423713055421844361000443
12864938683278671740537145998360961546653259485195807
165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443
Sum of the reciprocals of first ten in sequence: 27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920805/27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920806</pre>
 
=={{header|Verilog}}==
<syntaxhighlight lang="verilog">
<lang Verilog>
module main;
integer i;
Line 890 ⟶ 1,436:
end
endmodule
</syntaxhighlight>
</lang>
{{out}}
<pre>10 primeros términos de la sucesión de sylvester:
Line 910 ⟶ 1,456:
=={{header|Wren}}==
{{libheader|Wren-big}}
<langsyntaxhighlight ecmascriptlang="wren">import "./big" for BigInt, BigRat
 
var sylvester = [BigInt.two]
Line 929 ⟶ 1,475:
System.print (sumRecip)
System.print("\nThe sum of their reciprocals as a decimal number (to 211 places) is:")
System.print(sumRecip.toDecimal(211))</langsyntaxhighlight>
 
{{out}}
337

edits