Catalan numbers/Pascal's triangle: Difference between revisions
Content deleted Content added
Added Algol 68 |
m →{{header|Wren}}: Changed to Wren S/H |
||
(84 intermediate revisions by 48 users not shown) | |||
Line 1:
{{task}}
;Task:
Print out the first '''15''' Catalan numbers by extracting them from Pascal's triangle.
;See:
* [https://archive.is/0IrNp Catalan Numbers and the Pascal Triangle]. <!-- Relation Pascal Triangle and the Catalan Numbers Radoslav Jovanovic --> This method enables calculation of Catalan Numbers using only addition and subtraction.
<!-- '''http://milan.milanovic.org/math/english/fibo/fibo4.html is broken. -->
* [http://mathworld.wolfram.com/CatalansTriangle.html Catalan's Triangle] for a Number Triangle that generates Catalan Numbers using only addition.
* Sequence [[oeis:A000108|A000108 on OEIS]] has a lot of information on Catalan Numbers.
;Related Tasks:
[[Pascal's triangle]]
<br><br>
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">V n = 15
V t = [0] * (n + 2)
t[1] = 1
L(i) 1 .. n
L(j) (i .< 1).step(-1)
t[j] += t[j - 1]
t[i + 1] = t[i]
L(j) (i + 1 .< 1).step(-1)
t[j] += t[j - 1]
print(t[i + 1] - t[i], end' ‘ ’)</syntaxhighlight>
{{out}}
<pre>
1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845
</pre>
=={{header|360 Assembly}}==
For maximum compatibility, this program uses only the basic instruction set.
<
USING CATALAN,R13,R12
SAVEAREA B STM-SAVEAREA(R15)
Line 97 ⟶ 122:
WTOBUF DC CL80' '
YREGS
END</
{{out}}
<pre style="height:20ex">00000001
Line 114 ⟶ 139:
02674440
09694845</pre>
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<syntaxhighlight lang="action!">INCLUDE "D2:REAL.ACT" ;from the Action! Tool Ki
DEFINE PTR="CARD"
DEFINE REALSIZE="6"
PTR FUNC GetItemAddr(PTR buf BYTE i)
RETURN (buf+REALSIZE*i)
PROC Main()
DEFINE COUNT="15"
BYTE ARRAY buf(102) ;(COUNT+2)*REALSIZE
REAL POINTER r1,r2
REAL c
BYTE i,j
Put(125) PutE() ;clear the screen
r1=GetItemAddr(buf,1)
IntToReal(1,r1)
FOR i=1 TO COUNT
DO
j=i+1
WHILE j>=2
DO
r1=GetItemAddr(buf,j)
r2=GetItemAddr(buf,j-1)
RealAdd(r1,r2,r1) ;t(j)==+t(j-1)
j==-1
OD
r1=GetItemAddr(buf,i)
r2=GetItemAddr(buf,i+1)
RealAssign(r1,r2) ;t(i+1)=t(i)
j=i+2
WHILE j>=2
DO
r1=GetItemAddr(buf,j)
r2=GetItemAddr(buf,j-1)
RealAdd(r1,r2,r1) ;t(j)==+t(j-1)
j==-1
OD
r1=GetItemAddr(buf,i)
r2=GetItemAddr(buf,i+1)
RealSub(r2,r1,c) ;c=t(i+1)-t(i)
PrintF("C(%B)=",i) PrintRE(c)
OD
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Catalan_numbers_Pascal's_triangle.png Screenshot from Atari 8-bit computer]
<pre>
C(1)=1
C(2)=2
C(3)=5
C(4)=14
C(5)=42
C(6)=132
C(7)=429
C(8)=1430
C(9)=4862
C(10)=16796
C(11)=58786
C(12)=208012
C(13)=742900
C(14)=2674440
C(15)=9694845
</pre>
=={{header|Ada}}==
Uses package Pascal from the Pascal triangle solution[[http://rosettacode.org/wiki/Pascal%27s_triangle#Ada]]
<
procedure Catalan is
Line 132 ⟶ 225:
Ada.Text_IO.Put(Integer'Image(Row(I+1)-Row(I+2)));
end loop;
end Catalan;</
{{out}}
<pre>1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845</pre>
=={{header|ALGOL 68}}==
{{trans|C++}}
<
[ 0 : n + 1 ]INT t;
t[0] := 0;
Line 149 ⟶ 241:
FOR j FROM i+1 BY -1 TO 2 DO t[j] := t[j] + t[j-1] OD;
print( ( whole( t[i+1] - t[i], 0 ), " " ) )
OD</
{{out}}
<pre>
1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845
</pre>
=={{header|ALGOL W}}==
<syntaxhighlight lang="algolw">begin
% print the first 15 Catalan numbers from Pascal's triangle %
integer n;
n := 15;
begin
integer array pascalLine ( 1 :: n + 1 );
% the Catalan numbers are the differences between the middle and middle - 1 numbers of the odd %
% lines of Pascal's triangle (lines with 3 or more numbers) %
% note - we only need to calculate the left side of the triangle %
pascalLine( 1 ) := 1;
for c := 2 until n + 1 do begin
% even line %
for i := c - 1 step -1 until 2 do pascalLine( i ) := pascalLine( i - 1 ) + pascalLine( i );
pascalLine( c ) := pascalLine( c - 1 );
% odd line %
for i := c step -1 until 2 do pascalLine( i ) := pascalLine( i - 1 ) + pascalLine( i );
writeon( i_w := 1, s_w := 0, " ", pascalLine( c ) - pascalLine( c - 1 ) )
end for_c
end
end.</syntaxhighlight>
{{out}}
<pre>
1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845
</pre>
=={{header|APL}}==
<syntaxhighlight lang="apl">
⍝ Based heavily on the J solution
CATALAN←{¯1↓↑-/1 ¯1↓¨(⊂⎕IO+0 0)⍉¨0 2⌽¨⊂(⎕IO-⍨⍳N){+\⍣⍺⊢⍵}⍤0 1⊢1⍴⍨N←⍵+2}
</syntaxhighlight>
{{out}}
<pre>
CATALAN 15
1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845
</pre>
=={{header|Arturo}}==
<syntaxhighlight lang="arturo">n: 15
t: new array.of:n+2 0
t\[1]: 1
loop 1..n 'i [
loop i..1 'j -> t\[j]: t\[j] + t\[j-1]
t\[i+1]: t\[i]
loop (i+1)..1 'j -> t\[j]: t\[j] + t\[j-1]
prints t\[i+1] - t\[i]
prints " "
]
print ""</syntaxhighlight>
{{out}}
<pre>1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845</pre>
=={{header|AutoHotkey}}==
{{works with|AutoHotkey_L}}
<
//
// smgs: 20th Feb, 2014
Line 186 ⟶ 332:
}
}
MsgBox % result</
{{out|Produces}}
<pre>
1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845
</pre>
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f CATALAN_NUMBERS_PASCALS_TRIANGLE.AWK
# converted from C
BEGIN {
printf("1")
for (n=2; n<=15; n++) {
num = den = 1
for (k=2; k<=n; k++) {
num *= (n + k)
den *= k
catalan = num / den
}
printf(" %d",catalan)
}
printf("\n")
exit(0)
}
</syntaxhighlight>
{{out}}
<pre>
1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845
</pre>
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
{{trans|MSX-BASIC}}
<syntaxhighlight lang="qbasic">10 HOME
20 n = 15
30 DIM t(n+2)
50 t(1) = 1
55 PRINT "The first 15 Catalan numbers are: "; CHR$(10)
60 FOR i = 1 TO n
70 FOR j = i TO 1 STEP -1 : t(j) = t(j) + t(j-1) : NEXT j
80 t(i+1) = t(i)
90 FOR j = i+1 TO 1 STEP -1 : t(j) = t(j) + t(j-1) : NEXT j
100 PRINT i; ": "; t(i+1) - t(i)
120 NEXT i
130 END</syntaxhighlight>
==={{header|Chipmunk Basic}}===
{{trans|MSX-BASIC}}
{{works with|Chipmunk Basic|3.6.4}}
<syntaxhighlight lang="qbasic">100 cls
110 n = 15
120 dim t(n+2)
130 t(1) = 1
140 print "The first 15 Catalan numbers are: ";chr$(10)
150 for i = 1 to n
160 for j = i to 1 step -1 : t(j) = t(j)+t(j-1) : next j
170 t(i+1) = t(i)
180 for j = i+1 to 1 step -1 : t(j) = t(j)+t(j-1) : next j
190 print using "###";i;": ";
200 print using "#########";t(i+1)-t(i)
210 next i
220 end</syntaxhighlight>
==={{header|GW-BASIC}}===
{{works with|PC-BASIC|any}}
{{works with|BASICA}}
{{works with|QBasic}}
{{works with|MSX BASIC}}
The [[#GW-BASIC|GW-BASIC]] solution works without any changes.
==={{header|MSX Basic}}===
{{works with|MSX BASIC|any}}
<syntaxhighlight lang="qbasic">100 CLS
110 N = 15
120 DIM T(N+2)
130 T(1) = 1
140 PRINT "The first 15 Catalan numbers are: "; CHR$(10)
150 FOR I = 1 TO N
160 FOR J = I TO 1 STEP -1 : T(J) = T(J) + T(J-1) : NEXT J
170 T(I+1) = T(I)
180 FOR J = I+1 TO 1 STEP -1 : T(J) = T(J) + T(J-1) : NEXT J
190 PRINT USING "###: #########";I; T(I+1) - T(I)
200 NEXT I
210 END</syntaxhighlight>
{{out}}
<pre>The first 15 Catalan numbers are:
1: 1
2: 2
3: 5
4: 14
5: 42
6: 132
7: 429
8: 1430
9: 4862
10: 16796
11: 58786
12: 208012
13: 742900
14: 2674440
15: 9694845</pre>
==={{header|QBasic}}===
The [[#MSX-BASIC|MSX-BASIC]] solution works without any changes.
==={{header|XBasic}}===
{{trans|MSX-BASIC}}
{{works with|Windows XBasic}}
<syntaxhighlight lang="qbasic">PROGRAM "Pascal's triangle"
VERSION "0.0000"
DECLARE FUNCTION Entry ()
FUNCTION Entry ()
N = 15
DIM T[N+2]
T[1] = 1
PRINT "The first 15 Catalan numbers are: "; CHR$(10)
FOR I = 1 TO N
FOR J = I TO 1 STEP -1
T[J] = T[J] + T[J-1]
NEXT J
T[I+1] = T[I]
FOR J = I+1 TO 1 STEP -1
T[J] = T[J] + T[J-1]
NEXT J
PRINT FORMAT$("###",I); ": "; FORMAT$("#########",(T[I+1] - T[I]))
NEXT I
END FUNCTION
END PROGRAM</syntaxhighlight>
==={{header|Yabasic}}===
{{trans|MSX-BASIC}}
<syntaxhighlight lang="vb">n = 15
dim t(n+2)
t(1) = 1
print "The first 15 Catalan numbers are: \n"
for i = 1 to n
for j = i to 1 step -1
t(j) = t(j) + t(j-1)
next j
t(i+1) = t(i)
for j = i+1 to 1 step -1
t(j) = t(j) + t(j-1)
next j
print i using("###");
print ": ";
print t(i+1)-t(i) using ("#########")
next i</syntaxhighlight>
=={{header|Batch File}}==
<
setlocal ENABLEDELAYEDEXPANSION
set n=15
Line 214 ⟶ 509:
)
)
pause</
{{Out}}
<pre style="height:20ex">1
Line 231 ⟶ 526:
2674440
9694845</pre>
=={{header|C}}==
<syntaxhighlight lang="c">
//This code implements the print of 15 first Catalan's Numbers
//Formula used:
// __n__
// | | (n + k) / k n>0
// k=2
#include <stdio.h>
#include <stdlib.h>
//the number of Catalan's Numbers to be printed
const int N = 15;
int main()
{
//loop variables (in registers)
register int k, n;
//necessarily ull for reach big values
unsigned long long int num, den;
//the nmmber
int catalan;
//the first is not calculated for the formula
printf("1 ");
//iterating from 2 to 15
for (n=2; n<=N; ++n) {
//initializaing for products
num = den = 1;
//applying the formula
for (k=2; k<=n; ++k) {
num *= (n+k);
den *= k;
catalan = num /den;
}
//output
printf("%d ", catalan);
}
//the end
printf("\n");
return 0;
}
</syntaxhighlight>
{{out}}
<pre>
1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845
</pre>
=={{header|C sharp|C#}}==
{{trans|C++}}
<syntaxhighlight lang="csharp">
int n = 15;
List<int> t = new List<int>() { 0, 1 };
for (int i = 1; i <= n; i++)
{
for (var j = i; j > 1; j--) t[j] += t[j - 1];
t.Add(t[i]);
for (var j = i + 1; j > 1; j--) t[j] += t[j - 1];
Console.Write(((i == 1) ? "" : ", ") + (t[i + 1] - t[i]));
}
</syntaxhighlight>
{{out|Produces}}
<pre>
1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845
</pre>
=={{header|C++}}==
<
//
// Nigel Galloway: June 9th., 2012
Line 248 ⟶ 612:
}
return 0;
}</
{{out|Produces}}
<pre>
1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845
</pre>
=={{header|Common Lisp}}==
<syntaxhighlight lang="lisp">(defun catalan (n)
"Return the n-th Catalan number"
(if (<= n 1) 1
(let ((result 2))
(dotimes (k (- n 2) result)
(setq result (* result (/ (+ n k 2) (+ k 2)))) ))))
(dotimes (n 15)
(print (catalan (1+ n))) )</syntaxhighlight>
{{out}}
<pre>1
2
5
14
42
132
429
1430
4862
16796
58786
208012
742900
2674440
9694845</pre>
=={{header|D}}==
{{trans|C++}}
<
import std.stdio;
Line 289 ⟶ 664:
write(t[i + 1] - t[i], ' ');
}
}</
{{out}}
<pre>1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845 </pre>
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle#Pascal Pascal].
=={{header|EasyLang}}==
{{trans|AWK}}
<syntaxhighlight lang="easylang">
print 1
for n = 2 to 15
num = 1
den = 1
for k = 2 to n
num *= n + k
den *= k
cat = num / den
.
print cat
.
</syntaxhighlight>
=={{header|EchoLisp}}==
<
(define dim 100)
(define-syntax-rule (Tidx i j) (+ i (* dim j)))
Line 310 ⟶ 703:
(remember 'T #(1))
</syntaxhighlight>
{{out}}
<
;; take elements on diagonal = Catalan numbers
(for ((i (in-range 0 16))) (write (T (Tidx i i))))
→ 1 1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845
</syntaxhighlight>
=={{header|EDSAC order code}}==
Rather than store a triangular array, this solution stores the right-hand half of the current row and updates it in place. It uses the third method in the link, e.g. once we have the half row (70, 56, 28, 8, 1), the Catalan number 42 appears as 70 - 28.
<syntaxhighlight lang="edsac">
[Catalan numbers from Pascal triangle, Rosetta Code website.
EDSAC program, Initial Orders 2]
..PZ [blank tape and terminator]
T54K [refer to working array with 'C']
P300F [address of working array]
T46K [to call print subroutine with 'G N']
P56F [address of print subroutine]
[Modification of library subroutine P7.
Prints non-negative integer, up to 10 digits, right-justified.
55 locations, load at even address.]
E25KTN
GKA3FT42@A47@T31@ADE10@T31@A48@T31@SDTDH44#@NDYFLDT4DS43@
TFH17@S17@A43@G23@UFS43@T1FV4DAFG50@SFLDUFXFOFFFSFL4FT4DA49@
T31@A1FA43@G20@XFP1024FP610D@524D!FO46@O26@XFO46@SFL8FT4DE39@
[Main program]
PK T200K GK
[Constants]
[0] PD [short constant 1]
[1] P2F [to inc address by 2]
[2] T#C [used in manufacturing EDSAC orders]
[3] MF [add to T order to make A order with same address]
[4] #F [set figures]
[5] &F [line feed]
[6] @F [carriage return]
[7] P7D [maximum n = 15]
[Variable]
[8] PF [n]
[Enter with acc = 0]
[9] O4@ [set teleprinter to figures]
T4#C T2#C T#C A@ TC [initialize first 3 terms to 1, 0, 0]
T8@ E58@ [set n := 0; jump to inc n and print C_n]
[Outer loop; here with n updated]
[17] TF A8@ [acc := latest n]
L1F A2@ T22@ [make and store order 'T 2n #C']
[22] T#C [sets term := 0; also used to test for end of loop]
A2@ [load 'T#C', initial value of order 31]
[Loop to convert e.g. (20, 15, 6, 1) to (35, 21, 7, 1); works left to right]
[24] U31@ A3@ U29@ A1@ T30@ [set up orders on next line]
[29] A#C A#C T#C [replaced by manufactured orders]
A31@ A1@ S22@ E38@ [inc address in order 31, jump out if done]
A22@ E24@ [not done, loop back]
[38] A22@ T48@ [initialize order 48]
[Loop to convert e.g. (35, 21, 7, 1) to (70, 56, 28, 8, 1); works right to left]
[40] TF A48@ A3@ U46@ S1@ T47@ [set up orders on next line]
[46] A#C A#C T#C [replaced by manufactured orders]
A48@ S1@ T48@ [dec address in order 48]
A2@ S48@ G40@ [test for done, loop back if not]
A#C LD T#C [double first term, e.g. 35 -> 70 (not done in loop)]
[Increment n and print Catalan number C_n]
[58] TD [clear 0D, ensures sandwich bit = 0]
A8@ A@ U8@ TF [inc n; set 0D := n by setting 0F := n]
A63@ GN [print n]
A#C S4#C TD A68@ GN [print Catalan number C_n, e.g. C_5 = 70 - 28 = 42]
O6@ O5@ [print CR, LF]
A8@ S7@ G17@ [test for maximum n, loop back if not]
[75] O4@ ZF [flush printer buffer; stop]
E9Z PF [define entry point; enter with acc = 0]
</syntaxhighlight>
{{out}}
<pre>
1 1
2 2
3 5
4 14
5 42
6 132
7 429
8 1430
9 4862
10 16796
11 58786
12 208012
13 742900
14 2674440
15 9694845
</pre>
=={{header|Elixir}}==
<
def numbers(num) do
{result,_} = Enum.reduce(1..num, {[],{0,1}}, fn i,{list,t0} ->
Line 334 ⟶ 808:
end
IO.inspect Catalan.numbers(15)</
{{out}}
Line 340 ⟶ 814:
[1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845]
</pre>
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
-module(catalin).
-compile(export_all).
mul(N,D,S,S)->
N2=N*(S+S),
D2=D*S,
K = N2 div D2 ;
mul(N,D,S,L)->
N2=N*(S+L),
D2=D*L,
K = mul(N2,D2,S,L+1).
catl(Ans,16) -> Ans;
catl(D,S)->
C=mul(1,1,S,2),
catl([D|C],S+1).
main()->
Ans=catl(1,2).
</syntaxhighlight>
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM CATALAN
Line 381 ⟶ 874:
END FOR
END PROGRAM
</syntaxhighlight>
{{out}}
<pre>
Line 400 ⟶ 893:
15 9694845
</pre>
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">
let mutable nm=uint64(1)
let mutable dm=uint64(1)
let mutable a=uint64(1)
printf "1, "
for i = 2 to 15 do
nm<-uint64(1)
dm<-uint64(1)
for k = 2 to i do
nm <-uint64( uint64(nm) * (uint64(i)+uint64(k)))
dm <-uint64( uint64(dm) * uint64(k))
let a = uint64(uint64(nm)/uint64(dm))
printf "%u"a
if(i<>15) then
printf ", "
</syntaxhighlight>
=={{header|Factor}}==
<syntaxhighlight lang="factor">USING: arrays grouping io kernel math prettyprint sequences ;
IN: rosetta-code.catalan-pascal
: next-row ( seq -- seq' )
2 clump [ sum ] map 1 prefix 1 suffix ;
: pascal ( n -- seq )
1 - { { 1 } } swap [ dup last next-row suffix ] times ;
15 2 * pascal [ length odd? ] filter [
dup length 1 = [ 1 ]
[ dup midpoint@ dup 1 + 2array swap nths first2 - ] if
pprint bl
] each drop</syntaxhighlight>
{{out}}
<pre>
1 1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440
</pre>
=={{header|FreeBASIC}}==
<
' compile with: fbc -s console
Line 454 ⟶ 983:
' empty keyboard buffer
While InKey <> ""
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
<pre>The first 15 Catalan numbers are
Line 476 ⟶ 1,005:
14: 2674440
15: 9694845</pre>
=={{header|Go}}==
{{trans|C++}}
<syntaxhighlight lang="go">package main
import "fmt"
func main() {
const n = 15
t := [n + 2]uint64{0, 1}
for i := 1; i <= n; i++ {
for j := i; j > 1; j-- {
t[j] += t[j-1]
}
t[i+1] = t[i]
for j := i + 1; j > 1; j-- {
t[j] += t[j-1]
}
fmt.Printf("%2d : %d\n", i, t[i+1]-t[i])
}
}</syntaxhighlight>
{{out}}
<pre>
1 : 1
2 : 2
3 : 5
4 : 14
5 : 42
6 : 132
7 : 429
8 : 1430
9 : 4862
10 : 16796
11 : 58786
12 : 208012
13 : 742900
14 : 2674440
15 : 9694845
</pre>
=={{header|Groovy}}==
{{trans|C}}
<syntaxhighlight lang="groovy">
class Catalan
{
public static void main(String[] args)
{
BigInteger N = 15;
BigInteger k,n,num,den;
BigInteger catalan;
print(1);
for(n=2;n<=N;n++)
{
num = 1;
den = 1;
for(k=2;k<=n;k++)
{
num = num*(n+k);
den = den*k;
catalan = num/den;
}
print(" " + catalan);
}
}
}
</syntaxhighlight>
{{out}}
<pre>
1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845
</pre>
=={{header|Haskell}}==
As required by the task this implementation extracts the Catalan numbers from Pascal's triangle, rather
than calculating them directly. Also, note that it (correctly) produces [1, 1] as the first two numbers.
<
-- Pascal's triangle.
Line 498 ⟶ 1,096:
main = do
ns <- fmap (map read) getArgs :: IO [Int]
mapM_ (print . flip take catalan) ns</
{{out}}
Line 505 ⟶ 1,103:
[1,1,2,5,14,42,132,429,1430,4862,16796,58786,208012,742900,2674440]
</pre>
=={{header|Icon}} and {{header|Unicon}}==
Line 511 ⟶ 1,108:
that aren't used.
<
procedure main(A)
limit := (integer(A[1])|15)+1
every write(right(binocoef(i := 2*seq(0)\limit,i/2)-binocoef(i,i/2+1),30))
end</
Sample run:
Line 538 ⟶ 1,135:
->
</pre>
=={{header|J}}==
<
{{out|Example use}}
<
1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845
</
A structured derivation of Catalan follows:
<
( PascalTriangle=. i. ((+/\@]^:[)) #&1 ) 5
1 1 1 1 1
Line 565 ⟶ 1,161:
Catalan
}:@:(}.@:((<0 1)&|:) - }:@:((<0 1)&|:@:(2&|.)))@:(i. +/\@]^:[ #&1)@:(2&+)</
=={{header|Java}}==
{{trans|C++}}
<
public static void main(String[] args) {
int N = 15;
Line 588 ⟶ 1,183:
}
}
}</
<pre>1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845</pre>
=={{header|JavaScript}}==
===ES5===
Iteration
{{trans|C++}}
<
for (var t = [0, 1], i = 1; i <= n; i++) {
}</
{{out}}
<pre>
Line 606 ⟶ 1,202:
</pre>
===ES6===
Functional composition
{{Trans|Haskell}}
<syntaxhighlight lang="javascript">(() => {
'use strict';
// CATALAN
// catalanSeries :: Int -> [Int]
let catalanSeries = n => {
let alternate = xs => xs.reduce(
(a, x, i) => i % 2 === 0 ? a.concat([x]) : a, []
),
diff = xs => xs.length > 1 ? xs[0] - xs[1] : xs[0];
return alternate(pascal(n * 2))
.map((xs, i) => diff(drop(i, xs)));
}
// PASCAL
// pascal :: Int -> [[Int]]
let pascal = n => until(
m => m.level <= 1,
m => {
let nxt = zipWith(
(a, b) => a + b, [0].concat(m.row), m.row.concat(0)
);
return {
row: nxt,
triangle: m.triangle.concat([nxt]),
level: m.level - 1
}
}, {
level: n,
row: [1],
triangle: [
[1]
]
}
)
.triangle;
// GENERIC FUNCTIONS
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
let zipWith = (f, xs, ys) =>
xs.length === ys.length ? (
xs.map((x, i) => f(x, ys[i]))
) : undefined;
// until :: (a -> Bool) -> (a -> a) -> a -> a
let until = (p, f, x) => {
let v = x;
while (!p(v)) v = f(v);
return v;
}
// drop :: Int -> [a] -> [a]
let drop = (n, xs) => xs.slice(n);
// tail :: [a] -> [a]
let tail = xs => xs.length ? xs.slice(1) : undefined;
return tail(catalanSeries(16));
})();</syntaxhighlight>
{{Out}}
<syntaxhighlight lang="javascript">[1,2,5,14,42,132,429,1430,4862,16796,58786,208012,742900,2674440,9694845]</syntaxhighlight>
=={{header|jq}}==
The first identity (C(2n,n) - C(2n, n-1)) given in the reference is used in accordance with the task description, but it would of course be more efficient to factor out C(2n,n) and use the expression C(2n,n)/(n+1). See also [[Catalan_numbers#jq]] for other alternatives.
Line 611 ⟶ 1,278:
''Warning'': jq uses IEEE 754 64-bit arithmetic,
so the algorithm used here for Catalan numbers loses precision for n > 30 and fails completely for n > 510.
<
if k > n / 2 then binomial(n; n-k)
else reduce range(1; k+1) as $i (1; . * (n - $i + 1) / $i)
Line 617 ⟶ 1,284:
# Direct (naive) computation using two numbers in Pascal's triangle:
def catalan_by_pascal: . as $n | binomial(2*$n; $n) - binomial(2*$n; $n-1);</
'''Example''':
(range(0;16), 30, 31, 510, 511) | [., catalan_by_pascal]
{{Out}}
<
[0,0]
[1,1]
Line 642 ⟶ 1,309:
[31,14544636039226880]
[510,5.491717746183512e+302]
[511,null]</
=={{header|Julia}}==
{{trans|Matlab}}
<syntaxhighlight lang="julia"># v0.6
function pascal(n::Int)
r = ones(Int, n, n)
for i in 2:n, j in 2:n
r[i, j] = r[i-1, j] + r[i, j-1]
end
return r
end
function catalan_num(n::Int)
p = pascal(n + 2)
p[n+4:n+3:end-1] - diag(p, 2)
end
@show catalan_num(15)</syntaxhighlight>
{{out}}
<pre>catalan_num(15) = [1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845]</pre>
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.1.2
import java.math.BigInteger
val ONE = BigInteger.ONE
fun pascal(n: Int, k: Int): BigInteger {
if (n == 0 || k == 0) return ONE
val num = (k + 1..n).fold(ONE) { acc, i -> acc * BigInteger.valueOf(i.toLong()) }
val den = (2..n - k).fold(ONE) { acc, i -> acc * BigInteger.valueOf(i.toLong()) }
return num / den
}
fun catalanFromPascal(n: Int) {
for (i in 1 until n step 2) {
val mi = i / 2 + 1
val catalan = pascal(i, mi) - pascal(i, mi - 2)
println("${"%2d".format(mi)} : $catalan")
}
}
fun main(args: Array<String>) {
val n = 15
catalanFromPascal(n * 2)
}</syntaxhighlight>
{{out}}
<pre>
1 : 1
2 : 2
3 : 5
4 : 14
5 : 42
6 : 132
7 : 429
8 : 1430
9 : 4862
10 : 16796
11 : 58786
12 : 208012
13 : 742900
14 : 2674440
15 : 9694845
</pre>
=={{header|Lua}}==
For each line of odd-numbered length from Pascal's triangle, print the middle number minus the one immediately to its right.
This solution is heavily based on the Lua code to generate Pascal's triangle from the page for that task.
<syntaxhighlight lang="lua">function nextrow (t)
local ret = {}
t[0], t[#t + 1] = 0, 0
for i = 1, #t do ret[i] = t[i - 1] + t[i] end
return ret
end
function catalans (n)
local t, middle = {1}
for i = 1, n do
middle = math.ceil(#t / 2)
io.write(t[middle] - (t[middle + 1] or 0) .. " ")
t = nextrow(nextrow(t))
end
end
catalans(15)</syntaxhighlight>
{{out}}
<pre>1 1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440</pre>
=={{header|M2000 Interpreter}}==
{{trans|FreeBasic}}
We have to add -1 in For x=2 to rows, because in FreeBasic when x=rows then inner loop never happen because end value for y is 1, so lower than start value 2. In M2000 this should run from 2 to 1, so we have to exclude this situation from outer loop, adding -1, and before loop we have to include en exit from sub if rows are less than 2.
We can define integer variables (16 bit), and we can use integer literals numbers using % as last char.
Inside triangle array we use decimal numbers, using @ for first literals, so all additions next produce decimals too.
We use & to pass by reference, here anarray, to sub, but because a sub can see anything in module we can change array name inside sub to same as triangle and we can remove arguments (including size).
<syntaxhighlight lang="m2000 interpreter">
Module CatalanNumbers {
Def Integer count, t_row, size=31
Dim triangle(1 to size, 1 to size)
\\ call sub
pascal_triangle(size, &triangle())
Print "The first 15 Catalan numbers are"
count = 1% : t_row = 2%
Do {
Print Format$("{0:0:-3}:{1:0:-15}", count, triangle(t_row, t_row) - triangle(t_row +1, t_row -1))
t_row++
count++
} Until count > 15
End
Sub pascal_triangle(rows As Integer, &Pas_tri())
Local x=0%, y=0%
For x = 1 To rows
Pas_tri( 1%, x ) = 1@
Pas_tri( x, 1% ) = 1@
Next x
if rows<2 then exit sub
For x = 2 To rows-1
For y = 2 To rows + 1 - x
Pas_tri(x, y) = pas_tri(x - 1 , y) + pas_tri(x, y - 1)
Next y
Next x
End Sub
}
CatalanNumbers
</syntaxhighlight>
{{out}}
<pre>
1: 1
2: 2
3: 5
4: 14
5: 42
6: 132
7: 429
8: 1430
9: 4862
10: 16796
11: 58786
12: 208012
13: 742900
14: 2674440
15: 9694845
</pre>
=={{header|Maple}}==
<syntaxhighlight lang="maple">catalan:=proc(n)
local i,a:=[1],C:=[1];
for i to n do
a:=[0,op(a)]+[op(a),0];
a:=[0,op(a)]+[op(a),0];
C:=[op(C),a[i+1]-a[i]];
od;
C
end:
catalan(10);
# [1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796]</syntaxhighlight>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
This builds the entire Pascal triangle that's needed and holds it in memory. Very inefficienct, but seems to be what is asked in the problem.
<
output = ConstantArray[1, Length[lastrow] + 1];
Do[
Line 661 ⟶ 1,492:
]
(* testing *)
catalannumbers[15]</
{{out}}
<pre>{1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845}</pre>
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang="matlab">n = 15;
p = pascal(n + 2);
p(n + 4 : n + 3 : end - 1)' - diag(p, 2)</syntaxhighlight>
{{Out}}
<pre>ans =
Line 686 ⟶ 1,517:
2674440
9694845</pre>
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">
/* The Catalan triangle can be generated using genmatrix */
genmatrix(lambda([n,k],if n>=k then binomial(n+k-1,k-1)-2*binomial(n+k-2,k-2) else 0),15,15)$
/* The Catalan numbers are in the main diagonal */
makelist(%[i,i],i,1,15);
</syntaxhighlight>
{{out}}
<pre>
[1,1,2,5,14,42,132,429,1430,4862,16796,58786,208012,742900,2674440]
</pre>
=={{header|Nim}}==
{{trans|Python}}
<
var t = newSeq[int](n + 2)
Line 697 ⟶ 1,541:
t[i+1] = t[i]
for j in countdown(i+1, 1): t[j] += t[j-1]
stdout.write t[i+1] - t[i], " "
stdout.write '\n'</syntaxhighlight>
{{Out}}
<pre>1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845 </pre>
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">
let catalan : int ref = ref 0 in
Printf.printf "%d ," 1 ;
for i = 2 to 9 do
let nm : int ref = ref 1 in
let den : int ref = ref 1 in
for k = 2 to i do
nm := (!nm)*(i+k);
den := (!den)*k;
catalan := (!nm)/(!den) ;
done;
print_int (!catalan); print_string "," ;
done;;
</syntaxhighlight>
{{out}}
<pre>
OUTPUT:
1 ,2,5,14,42,132,429,1430,4862
</pre>
=={{header|Oforth}}==
<syntaxhighlight lang="oforth">import: mapping
: pascal( n -- [] )
[ 1 ] n #[ dup [ 0 ] + [ 0 ] rot + zipWith( #+ ) ] times ;
: catalan( n -- m )
n 2 * pascal at( n 1+ ) n 1+ / ;</syntaxhighlight>
{{out}}
<pre>
>#catalan 15 seq map
[1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845]
</pre>
=={{header|PARI/GP}}==
<
{{out}}
<pre>%1 = [1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845]</pre>
=={{header|Pascal}}==
<
Program CatalanNumbers
type
tElement = Uint64;
var
Line 752 ⟶ 1,621:
For i := 1 to L do
Writeln(i:3,Catalan[i]:20);
end.</
<pre> 1 1
2 2
Line 770 ⟶ 1,639:
</pre>
=={{header|Perl}}==
{{trans|C++}}
<
my @t = (0, 1);
for(my $i = 1; $i <= N; $i++) {
Line 780 ⟶ 1,648:
for(my $j = $i+1; $j>1; $j--) { $t[$j] += $t[$j-1] }
print $t[$i+1] - $t[$i], " ";
}</
{{out}}
<pre>1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845</pre>
Line 786 ⟶ 1,654:
After the 28th Catalan number, this overflows 64-bit integers. We could add <tt>use bigint;</tt> <tt>use Math::GMP ":constant";</tt> to make it work, albeit not at a fast pace. However we can use a module to do it much faster:
{{libheader|ntheory}}
<
print join(" ", map { binomial( 2*$_, $_) / ($_+1) } 1 .. 1000), "\n";</
The <tt>Math::Pari</tt> module also has a binomial, but isn't as fast and overflows its stack after 3400.
=={{header|Phix}}==
Calculates the minimum pascal triangle in minimum memory. Inspired by the comments in, but not the code of the FreeBasic example
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">constant</span> <span style="color: #000000;">N</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">15</span> <span style="color: #000080;font-style:italic;">-- accurate to 30, nan/inf for anything over 514 (gmp version is below).</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">catalan</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{},</span> <span style="color: #000080;font-style:italic;">-- (>=1 only)</span>
<span style="color: #000000;">p</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">N</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">p1</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">N</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">p1</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]*</span><span style="color: #000000;">2</span>
<span style="color: #000000;">catalan</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">catalan</span><span style="color: #0000FF;">,</span><span style="color: #000000;">p1</span><span style="color: #0000FF;">-</span><span style="color: #000000;">p</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">])</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">N</span><span style="color: #0000FF;">-</span><span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">p1</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
<span style="color: #000000;">p</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">p1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000080;font-style:italic;">-- ?p[1..N-i+1]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">catalan</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 845 ⟶ 1,681:
</pre>
Explanatory comments to accompany the above
<
--' 1 1 1 1 1 1
--' 1 2 3 4 5 6
Line 877 ⟶ 1,713:
-- 10 15 21
-- 35 56
-- 126 (unused)</
=== gmp version ===
{{libheader|Phix/mpfr}}
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">\</span><span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">catalanB</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- very very fast!</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">catalan</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_inits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">p</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_inits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">mpz</span> <span style="color: #000000;">p1</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #000000;">p1</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">n</span> <span style="color: #008080;">do</span>
<span style="color: #7060A8;">mpz_mul_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">p1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">p</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">],</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpz_sub</span><span style="color: #0000FF;">(</span><span style="color: #000000;">catalan</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">p1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">p</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">])</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #7060A8;">mpz_add</span><span style="color: #0000FF;">(</span><span style="color: #000000;">p1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">p1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">p</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">])</span>
<span style="color: #7060A8;">mpz_set</span><span style="color: #0000FF;">(</span><span style="color: #000000;">p</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">],</span><span style="color: #000000;">p1</span><span style="color: #0000FF;">)</span>
<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: #008080;">return</span> <span style="color: #000000;">catalan</span><span style="color: #0000FF;">[</span><span style="color: #000000;">n</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</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;">"%d: %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">100</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">mpz_get_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">catalanB</span><span style="color: #0000FF;">(</span><span style="color: #000000;">100</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;">"%d: %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">250</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">mpz_get_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">catalanB</span><span style="color: #0000FF;">(</span><span style="color: #000000;">250</span><span style="color: #0000FF;">)))})</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
100: 89651994709013149668...20837521538745909320 (57 digits)
250: 46511679596923379649...69029457769094808256 (147 digits)
</pre>
The above is significantly faster than the equivalent(s) on [[Catalan_numbers#Phix|Catalan_numbers]],
a quick comparison showing the latter getting exponentially worse (then again I memoised the slowest recursive version):
<pre>
800 2000 4000 8000
catalanB: 0.6s 3.5s 14.5s 64s
catalan2m: 0.7s 7.0s 64.9s 644s
</pre>
=={{header|PicoLisp}}==
<
(let f
'((N)
Line 923 ⟶ 1,766:
(bino (* 2 N) N)
(bino (* 2 N) (inc N)) ) ) )
(bye)</
=={{header|PureBasic}}==
{{trans|C}}
<syntaxhighlight lang="purebasic">#MAXNUM = 15
Declare catalan()
If OpenConsole("Catalan numbers")
catalan()
Input()
End 0
Else
End -1
EndIf
Procedure catalan()
Define k.i, n.i, num.d, den.d, cat.d
Print("1 ")
For n=2 To #MAXNUM
num=1 : den =1
For k=2 To n
num * (n+k)
den * k
cat = num / den
Next
Print(Str(cat)+" ")
Next
EndProcedure</syntaxhighlight>
{{out}}
<pre>
1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845</pre>
=={{header|Python}}==
===Procedural===
{{trans|C++}}
<
>>> t = [0] * (n + 2)
>>> t[1] = 1
Line 938 ⟶ 1,812:
1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845
>>> </
{{Works with|Python|2.7}}
<
nm = dm = 1
for k in range(2, n+1):
Line 949 ⟶ 1,823:
print [catalan_number(n) for n in range(1, 16)]
[1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845]</
===Composition of pure functions===
Note that sequence [[oeis:A000108|A000108]] on OEIS (referenced in the task description) confirms that the first four Catalan numbers are indeed 1, 1, 2, 5 ...
(Several scripts on this page appear to lose the first 1).
{{Trans|Haskell}}
{{Works with|Python|3.7}}
<syntaxhighlight lang="python">'''Catalan numbers from Pascal's triangle'''
from itertools import (islice)
from operator import (add)
# nCatalans :: Int -> [Int]
def nCatalans(n):
'''The first n Catalan numbers,
derived from Pascal's triangle.'''
# diff :: [Int] -> Int
def diff(xs):
'''Difference between the first two items in the list,
if its length is more than one.
Otherwise, the first (only) item in the list.'''
return (
xs[0] - (xs[1] if 1 < len(xs) else 0)
) if xs else None
return list(map(
compose(diff)(uncurry(drop)),
enumerate(map(fst, take(n)(
everyOther(
pascalTriangle()
)
)))
))
# pascalTriangle :: Gen [[Int]]
def pascalTriangle():
'''A non-finite stream of
Pascal's triangle rows.'''
return iterate(nextPascal)([1])
# nextPascal :: [Int] -> [Int]
def nextPascal(xs):
'''A row of Pascal's triangle
derived from a preceding row.'''
return zipWith(add)([0] + xs)(xs + [0])
# TEST ----------------------------------------------------
# main :: IO ()
def main():
'''First 16 Catalan numbers.'''
print(
nCatalans(16)
)
# GENERIC -------------------------------------------------
# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
'''Right to left function composition.'''
return lambda f: lambda x: g(f(x))
# drop :: Int -> [a] -> [a]
# drop :: Int -> String -> String
def drop(n):
'''The sublist of xs beginning at
(zero-based) index n.'''
def go(xs):
if isinstance(xs, list):
return xs[n:]
else:
take(n)(xs)
return xs
return lambda xs: go(xs)
# everyOther :: Gen [a] -> Gen [a]
def everyOther(g):
'''Every other item of a generator stream.'''
while True:
yield take(1)(g)
take(1)(g) # Consumed, not yielded.
# fst :: (a, b) -> a
def fst(tpl):
'''First component of a pair.'''
return tpl[0]
# 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 lambda x: go(x)
# take :: Int -> [a] -> [a]
# take :: Int -> String -> String
def take(n):
'''The prefix of xs of length n,
or xs itself if n > length xs.'''
return lambda xs: (
xs[0:n]
if isinstance(xs, list)
else list(islice(xs, n))
)
# uncurry :: (a -> b -> c) -> ((a, b) -> c)
def uncurry(f):
'''A function over a tuple
derived from a curried function.'''
return lambda xy: f(xy[0])(
xy[1]
)
# zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
def zipWith(f):
'''A list constructed by zipping with a
custom function, rather than with the
default tuple constructor.'''
return lambda xs: lambda ys: (
list(map(f, xs, ys))
)
# MAIN ---
if __name__ == '__main__':
main()</syntaxhighlight>
{{Out}}
<pre>[1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845]</pre>
=={{header|Quackery}}==
<syntaxhighlight lang="quackery"> [ [] 0 rot 0 join
witheach
[ tuck +
rot join swap ]
drop ] is nextline ( [ --> [ )
[ ' [ 1 ] swap times
[ nextline nextline
dup dup size 2 /
split nip
2 split drop
do - echo sp ]
drop ] is catalan ( n --> )
15 catalan</syntaxhighlight>
{{out}}
<pre>1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845</pre>
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
Line 964 ⟶ 2,002:
;; -> '(1 1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900
;; 2674440 9694845)
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2015.12}}
<syntaxhighlight lang="raku" line>constant @pascal = [1], -> @p { [0, |@p Z+ |@p, 0] } ... *;
constant @catalan = gather for 2, 4 ... * -> $ix {
my @row := @pascal[$ix];
my $mid = +@row div 2;
take [-] @row[$mid, $mid+1]
}
.say for @catalan[^20];</syntaxhighlight>
{{out}}
<pre>1
2
5
14
42
132
429
1430
4862
16796
58786
208012
742900
2674440
9694845
35357670
129644790
477638700
1767263190
6564120420</pre>
=={{header|REXX}}==
===explicit subscripts===
All of the REXX program examples can handle arbitrary large numbers.
<
parse arg N .
@.=0; @.1=1 /*stem array default; define 1st value.*/
do i=1 for N; ip=i+1
do j=i by -1 for N; jm=j-1; @.j=@.j+@.jm; end /*j*/
@.ip=@.i; do k=ip by -1 for N; km=k-1; @.k=@.k+@.km; end /*k*/
say @.ip - @.i /*display the Ith Catalan number. */
end /*i*/ /*stick a fork in it, we're all done. */</
<pre>
1
Line 999 ⟶ 2,070:
===implicit subscripts===
<
parse arg N .
@.=0; @.1=1 /*stem array default; define 1st value.*/
do i=1 for N;
do j=i by -1 for N; @.j=@.j+@(j-1); end /*j*/
@.ip=@.i; do k=ip by -1 for N; @.k=@.k+@(k-1); end /*k*/
say @.ip - @.i
end /*i*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
@: parse arg !; return @.! /*return the value of @.[arg(1)] */</syntaxhighlight>
'''output''' is the same as the 1<sup>st</sup> version.
===using binomial coefficients===
<
parse arg N .
numeric digits max(9, N%2 + N%8) /*so we can handle huge Catalan numbers*/
do j=1 for N /* [↓] display N Catalan numbers. */
say comb(j+j, j) % (j+1) /*display the Jth Catalan number. */
end /*j*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
!: procedure; parse arg z; _=1; do j=1 for arg(1); _=_*j; end; return _
/*──────────────────────────────────────────────────────────────────────────────────────*/
comb: procedure; parse arg x,y; if x=y then return 1; if y>x then return 0
if x-y<y then y=x-y; _=1; do j=x-y+1 to x; _=_*j; end; return _/!(y)</syntaxhighlight>
'''output''' is the same as the 1<sup>st</sup> version.
===binomial coefficients, memoized===
This REXX version uses memoization for the calculation of factorials.
<
parse arg N .
numeric digits max(9, N%2 + N%8) /*so we can handle huge Catalan numbers*/
!.=.
say comb(j+j, j) % (j+1)
end /*j*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
!: procedure expose !.;
do j=1 for arg(1); _=_*j; end; !.z=_;
/*──────────────────────────────────────────────────────────────────────────────────────*/
comb: procedure expose !.; parse arg x,y; if x=y then return 1; if y>x then return 0
if x-y<y then y=x-y; _=1; do j=x-y+1 to x; _=_*j; end; return _/!(y)</syntaxhighlight>
'''output''' is the same as the 1<sup>st</sup> version. <br><br>
=={{header|Ring}}==
<syntaxhighlight lang="ring">
n=15
cat = list(n+2)
cat[1]=1
for i=1 to n
for j=i+1 to 2 step -1
cat[j]=cat[j]+cat[j-1]
next
cat[i+1]=cat[i]
for j=i+2 to 2 step -1
cat[j]=cat[j]+cat[j-1]
next
see "" + (cat[i+1]-cat[i]) + " "
next
</syntaxhighlight>
Output:
<pre>
1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845
</pre>
=={{header|RPL}}==
We have taken the opportunity provided by the task to develop a routine that recursively computes Pascal's triangle.
If the challenge was to look for high Catalan numbers, memoizing the triangle would make sense.
{{works with|Halcyon Calc|4.2.8}}
{| class="wikitable"
! RPL code
! Comment
|-
|
≪ '''IF THEN''' LAST 1 + → n1
≪ n1 2 - '''PASLIN'''
{ } n1 + RDM
DUP ARRY→ DROP n1 ROLLD n1 →ARRY +
≫ '''ELSE''' [ 1 ] '''END'''
≫ ‘'''PASLIN'''’ STO
≪
DUP DUP + '''PASLIN'''
SWAP GETI ROT ROT GET SWAP -
≫ ‘'''CATLN'''’ STO
|
'''PASLIN''' ''( n -- [ 1..(n,p)..1 ] ) ''
get previous line
add a zero at tail
duplicate it, rotate right coeffs and sum
'''CATLN''' ''( n -- C(n) )''
get Pascal_line(2n)
return line[n+1]-line[n]
|}
{{in}}
<pre>
≪ { } 1 15 FOR j CATLN j + NEXT ≫ EVAL
</pre>
{{out}}
<pre>
1: { 1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845 }
</pre>
Runs in 119 seconds on an HP-28S.
===Fast, idiomatic approach===
Using the built-in <code>COMB</code> function, which returns coefficients of Pascal's triangle:
≪ { } 1 15 '''FOR''' j
j DUP + j COMB LAST 1 - COMB - + '''NEXT'''
≫ EVAL
Same output than above, runs in 2.4 seconds on an HP-28S.
=={{header|Ruby}}==
<
t = [0, 1] #grows as needed
(1..num).map do |i|
Line 1,061 ⟶ 2,199:
end
p catalan(15)</
{{out}}
<pre>
Line 1,068 ⟶ 2,206:
=={{header|Run BASIC}}==
<
dim t(n+2)
t(1) = 1
Line 1,076 ⟶ 2,214:
for j = i+1 to 1 step -1: t(j) = t(j) + t(j-1 : next j
print t(i+1) - t(i);" ";
next i</
{{out}}
<pre>1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845 </pre>
=={{header|Rust}}==
<syntaxhighlight lang="rust">
fn main()
{let n=15usize;
let mut t= [0; 17];
t[1]=1;
let mut j:usize;
for i in 1..n+1
{
j=i;
loop{
if j==1{
break;
}
t[j]=t[j] + t[j-1];
j=j-1;
}
t[i+1]= t[i];
j=i+1;
loop{
if j==1{
break;
}
t[j]=t[j] + t[j-1];
j=j-1;
}
print!("{} ", t[i+1]-t[i]);
}
}
</syntaxhighlight>
{{out}}
<pre>1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845 </pre>
=={{header|Scala}}==
<syntaxhighlight lang="scala">def catalan(n: Int): Int =
if (n <= 1) 1
else (0 until n).map(i => catalan(i) * catalan(n - i - 1)).sum
(1 to 15).map(catalan(_))</syntaxhighlight>
{{Out}}See it in running in your browser by [https://scastie.scala-lang.org/2ybpRZxCTOyrx3mIy8yIDw Scastie (JVM)].
=={{header|Scilab}}==
<syntaxhighlight lang="text">n=15
t=zeros(1,n+2)
t(1)=1
Line 1,093 ⟶ 2,270:
end
disp(t(i+1)-t(i))
end</
{{out}}
<pre style="height:20ex"> 1.
Line 1,110 ⟶ 2,287:
2674440.
9694845. </pre>
=={{header|Seed7}}==
<
const proc: main is func
Line 1,132 ⟶ 2,308:
end for;
writeln;
end func;</
{{out}}
Line 1,138 ⟶ 2,314:
1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845
</pre>
=={{header|Sidef}}==
{{trans|Ruby}}
<
var t = [0, 1]
t[i+1] = t[i]
t[i+1] - t[i]
}
}
say catalan(15).join(' ')
{{out}}
<pre>1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845</pre>
=={{header|smart BASIC}}==
<syntaxhighlight lang="qbasic">PRINT "Catalan Numbers from Pascal's Triangle"!PRINT
x = 15
DIM t(x+2)
t(1) = 1
FOR n = 1 TO x
FOR m = n TO 1 STEP -1
t(m) = t(m) + t(m-1)
NEXT m
t(n+1) = t(n)
FOR m = n+1 TO 1 STEP -1
t(m) = t(m) + t(m-1)
NEXT m
PRINT n,"#######":t(n+1) - t(n)
NEXT n</syntaxhighlight>
=={{header|Tcl}}==
<
set result {}
array set t {0 0 1 1}
Line 1,170 ⟶ 2,357:
}
puts [catalan 15]</
{{out}}
<pre>1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845</pre>
=={{header|TI-83 BASIC}}==
<
15→N
seq(0,I,1,N+2)→L1
Line 1,188 ⟶ 2,374:
End
Disp L1(I+1)-L1(I)
End</
{{out}}
<pre> 1
Line 1,206 ⟶ 2,392:
9694845
Done </pre>
=={{header|Vala}}==
{{trans|C++}}
<syntaxhighlight lang="vala">void main() {
const int N = 15;
uint64[] t = {0, 1};
for (int i = 1; i <= N; i++) {
for (int j = i; j > 1; j--) t[j] = t[j] + t[j - 1];
t[i + 1] = t[i];
for (int j = i + 1; j > 1; j--) t[j] = t[j] + t[j - 1];
print(@"$(t[i + 1] - t[i]) ");
}
print("\n");
}</syntaxhighlight>
{{out}}
<pre>
1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845
</pre>
=={{header|VBScript}}==
To run in console mode with cscript.
<
if Wscript.arguments.count=1 then
n=Wscript.arguments.item(0)
Line 1,228 ⟶ 2,431:
next 'j
Wscript.echo t(i+1)-t(i)
next 'i</
=={{header|Visual Basic}}==
{{trans|Rexx}}
{{works with|Visual Basic|VB6 Standard}}
<syntaxhighlight lang="vb">
Sub catalan()
Const n = 15
Line 1,250 ⟶ 2,452:
Next i
End Sub 'catalan
</syntaxhighlight>
{{Out}}
<pre style="height:20ex">
Line 1,268 ⟶ 2,470:
2674440
9694845
</pre>
=={{header|Wren}}==
{{trans|C++}}
<syntaxhighlight lang="wren">var n = 15
var t = List.filled(n+2, 0)
t[1] = 1
for (i in 1..n) {
if (i > 1) for (j in i..2) t[j] = t[j] + t[j-1]
t[i+1] = t[i]
if (i > 0) for (j in i+1..2) t[j] = t[j] + t[j-1]
System.write("%(t[i+1]-t[i]) ")
}
System.print()</syntaxhighlight>
{{out}}
<pre>
1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845
</pre>
=={{header|XPL0}}==
{{trans|C++}}
<syntaxhighlight lang "XPL0">def N = 15;
int T(N+2), I, J;
[T(0):= 0; T(1):= 1;
for I:= 1 to N do
[for J:= I downto 2 do T(J):= T(J) + T(J-1);
T(I+1):= T(I);
for J:= I+1 downto 2 do T(J):= T(J) + T(J-1);
IntOut(0, T(I+1) - T(I)); ChOut(0, ^ );
];
]</syntaxhighlight>
{{out}}
<pre>
1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845 </pre>
=={{header|Zig}}==
Uses comptime functionality to compile Pascal's triangle into the object code, then at runtime, it's simply a table lookup. (uses code from [[AKS test for primes|AKS primality task]].)
<syntaxhighlight lang="zig">
const std = @import("std");
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
var n: u32 = 1;
while (n <= 15) : (n += 1) {
const row = binomial(n * 2).?;
try stdout.print("{d:2} {d:8}\n", .{ n, row[n] - row[n + 1] });
}
}
pub fn binomial(n: u32) ?[]const u64 {
if (n >= rmax)
return null
else {
const k = n * (n + 1) / 2;
return pascal[k .. k + n + 1];
}
}
const rmax = 68;
// evaluated and created at compile-time
const pascal = build: {
@setEvalBranchQuota(100_000);
var coefficients: [(rmax * (rmax + 1)) / 2]u64 = undefined;
coefficients[0] = 1;
var j: u32 = 0;
var k: u32 = 1;
var n: u32 = 1;
while (n < rmax) : (n += 1) {
var prev = coefficients[j .. j + n];
var next = coefficients[k .. k + n + 1];
next[0] = 1;
var i: u32 = 1;
while (i < n) : (i += 1)
next[i] = prev[i] + prev[i - 1];
next[i] = 1;
j = k;
k += n + 1;
}
break :build coefficients;
};
</syntaxhighlight>
{{Out}}
<pre>
1 1
2 2
3 5
4 14
5 42
6 132
7 429
8 1430
9 4862
10 16796
11 58786
12 208012
13 742900
14 2674440
15 9694845
</pre>
=={{header|zkl}}==
{{trans|PARI/GP}} using binomial coefficients.
<
(1).pump(15,List,fcn(n){ binomial(2*n,n)-binomial(2*n,n+1) })</
{{out}}
<pre>
L(1,2,5,14,42,132,429,1430,4862,16796,58786,208012,742900,2674440,9694845)
</pre>
=={{header|ZX Spectrum Basic}}==
{{trans|C++}}
<syntaxhighlight lang="zxbasic">10 LET N=15
20 DIM t(N+2)
30 LET t(2)=1
40 FOR i=2 TO N+1
50 FOR j=i TO 2 STEP -1: LET t(j)=t(j)+t(j-1): NEXT j
60 LET t(i+1)=t(i)
70 FOR j=i+1 TO 2 STEP -1: LET t(j)=t(j)+t(j-1): NEXT j
80 PRINT t(i+1)-t(i);" ";
90 NEXT i</syntaxhighlight>
|