SUNY Geneseo Department of Mathematics
Tuesday, September 22
Math 303
Fall 2015
Prof. Doug Baldwin
factorial( n ) factorial( n )
if n = 0 f = 1
return 1 for i = 1 to n
else f = f * i
return n * factorial(n-1) return f
times( x, y ) // x is a natural number
if x = 0
// base case
return 0
else if x > 0 and even
// recursive case 1
return times( x/2, 2*y )
else // x > 0 and odd
// recursive case 2
return times( x-1, y ) + y
function product = times( x, y )
if x == 0
product = 0;
elseif mod(x,2) == 0
product = times( x/2, 2*y);
else
product = times( x-1, y ) + y;
end
end
>> times( 3, 4 )
ans =
12
>> times( 0, 4 )
ans =
0
>> times( 16, 3 )
ans =
48
toPeano( n ) // returns string
if n = 0
return “0”
else
return concatenate( “s(”, toPeano(n-1), “)” )
function p = toPeano( n )
if n == 0
p = '0';
else
p = [ 's(' toPeano(n-1) ')' ];
end
end
>> toPeano( 11 )
ans =
s(s(s(s(s(s(s(s(s(s(s(0)))))))))))
>> toPeano( 0 )
ans =
0