uh, yeah, that's what I meant ... darn'd quickie code always bites me in the
butt ...
j.
···
On 12/23/05, Jacob Fugal <lukfugl@gmail.com> wrote:
On 12/23/05, Jeff Wood <jeff.darklight@gmail.com> wrote:
> # complete recursive:
>
> def factorial( x )
> return 0 if x < 1
> x * factorial( x - 1 )
> end
>
> # tail-recursive:
>
> def factorial( x, sum = 1 )
> return 0 if x < 1
> factorial( ( x - 1 ), ( sum * x ) )
> end
>
> # iterative:
>
> def factorial( x )
> sum = 1
> for i in (1..x).to_a
> sum *= i
> end
> end
With bugfixes:
# complete recursive:
def factorial( x )
return 1 if x < 1
x * factorial( x - 1 )
end
# tail-recursive:
def factorial( x, sum = 1 )
return sum if x < 1
factorial( ( x - 1 ), ( sum * x ) )
end
# iterative:
def factorial( x )
sum = 1
for i in (1..x).to_a
sum *= i
end
sum
end