1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
|
#!./perl
#
# test recursive functions.
#
print "1..25\n";
sub gcd ($$) {
return gcd($_[0] - $_[1], $_[1]) if ($_[0] > $_[1]);
return gcd($_[0], $_[1] - $_[0]) if ($_[0] < $_[1]);
$_[0];
}
sub factorial ($) {
$_[0] < 2 ? 1 : $_[0] * factorial($_[0] - 1);
}
sub fibonacci ($) {
$_[0] < 2 ? 1 : fibonacci($_[0] - 2) + fibonacci($_[0] - 1);
}
# Highly recursive, highly aggressive.
# Kids, don't try this at home.
#
# For example ackermann(4,1) will take quite a long time.
# It will simply eat away your memory. Trust me.
sub ackermann ($$) {
return $_[1] + 1 if ($_[0] == 0);
return ackermann($_[0] - 1, 1) if ($_[1] == 0);
ackermann($_[0] - 1, ackermann($_[0], $_[1] - 1));
}
# Highly recursive, highly boring.
sub takeuchi ($$$) {
$_[1] < $_[0] ?
takeuchi(takeuchi($_[0] - 1, $_[1], $_[2]),
takeuchi($_[1] - 1, $_[2], $_[0]),
takeuchi($_[2] - 1, $_[0], $_[1]))
: $_[2];
}
print 'not ' unless (($d = gcd(1147, 1271)) == 31);
print "ok 1\n";
print "# gcd(1147, 1271) = $d\n";
print 'not ' unless (($d = gcd(1908, 2016)) == 36);
print "ok 2\n";
print "# gcd(1908, 2016) = $d\n";
print 'not ' unless (($f = factorial(10)) == 3628800);
print "ok 3\n";
print "# factorial(10) = $f\n";
print 'not ' unless (($f = factorial(factorial(3))) == 720);
print "ok 4\n";
print "# factorial(factorial(3)) = $f\n";
print 'not ' unless (($f = fibonacci(10)) == 89);
print "ok 5\n";
print "# fibonacci(10) = $f\n";
print 'not ' unless (($f = fibonacci(fibonacci(7))) == 17711);
print "ok 6\n";
print "# fibonacci(fibonacci(7)) = $f\n";
$i = 7;
@ack = qw(1 2 3 4 2 3 4 5 3 5 7 9 5 13 29 61);
for $x (0..3) {
for $y (0..3) {
$a = ackermann($x, $y);
print 'not ' unless ($a == shift(@ack));
print "ok ", $i++, "\n";
print "# ackermann($x, $y) = $a\n";
}
}
($x, $y, $z) = (18, 12, 6);
print 'not ' unless (($t = takeuchi($x, $y, $z)) == $z + 1);
print "ok ", $i++, "\n";
print "# takeuchi($x, $y, $z) = $t\n";
{
sub get_first1 {
get_list1(@_)->[0];
}
sub get_list1 {
return [24] unless $_[0];
my $u = get_first1(0);
[$u];
}
my $x = get_first1(1);
print "ok $x\n";
}
{
sub get_first2 {
return get_list2(@_)->[0];
}
sub get_list2 {
return [25] unless $_[0];
my $u = get_first2(0);
return [$u];
}
my $x = get_first2(1);
print "ok $x\n";
}
$i = 26;
|