4 # test recursive functions.
10 return gcd($_[0] - $_[1], $_[1]) if ($_[0] > $_[1]);
11 return gcd($_[0], $_[1] - $_[0]) if ($_[0] < $_[1]);
16 $_[0] < 2 ? 1 : $_[0] * factorial($_[0] - 1);
20 $_[0] < 2 ? 1 : fibonacci($_[0] - 2) + fibonacci($_[0] - 1);
23 # Highly recursive, highly aggressive.
24 # Kids, don't try this at home.
25 # For example ackermann(4,0) will take quite a long time.
27 # In fact, the current Perl, 5.004, will complain loudly:
28 # "Deep recursion on subroutine." (see perldiag) when
29 # computing the ackermann(4,0) because the recursion will
30 # become so deep (>100 levels) that Perl suspects the script
31 # has been lost in an infinite recursion.
34 return $_[1] + 1 if ($_[0] == 0);
35 return ackermann($_[0] - 1, 1) if ($_[1] == 0);
36 ackermann($_[0] - 1, ackermann($_[0], $_[1] - 1));
39 # Highly recursive, highly boring.
43 takeuchi(takeuchi($_[0] - 1, $_[1], $_[2]),
44 takeuchi($_[1] - 1, $_[2], $_[0]),
45 takeuchi($_[2] - 1, $_[0], $_[1]))
49 print 'not ' unless (($d = gcd(1147, 1271)) == 31);
51 print "# gcd(1147, 1271) = $d\n";
53 print 'not ' unless (($d = gcd(1908, 2016)) == 36);
55 print "# gcd(1908, 2016) = $d\n";
57 print 'not ' unless (($f = factorial(10)) == 3628800);
59 print "# factorial(10) = $f\n";
61 print 'not ' unless (($f = factorial(factorial(3))) == 720);
63 print "# factorial(factorial(3)) = $f\n";
65 print 'not ' unless (($f = fibonacci(10)) == 89);
67 print "# fibonacci(10) = $f\n";
69 print 'not ' unless (($f = fibonacci(fibonacci(7))) == 17711);
71 print "# fibonacci(fibonacci(7)) = $f\n";
75 @ack = qw(1 2 3 4 2 3 4 5 3 5 7 9 5 13 29 61);
79 $a = ackermann($x, $y);
80 print 'not ' unless ($a == shift(@ack));
81 print "ok ", $i++, "\n";
82 print "# ackermann($x, $y) = $a\n";
86 ($x, $y, $z) = (18, 12, 6);
88 print 'not ' unless (($t = takeuchi($x, $y, $z)) == $z + 1);
89 print "ok ", $i++, "\n";
90 print "# takeuchi($x, $y, $z) = $t\n";