From: Gary Thomas Date: 2007-04-18T13:37:34+09:00 Subject: Re: factorial in ruby For large enough n it will also overflow the number. Probably the most efficient way would be to use a loop up to some (not very large) number, to use Stirling's approximation or its extension up to some larger number, and throw an overfow exception for anything larger than that. Cheers Gary Thomas > -----Original Message----- > From: David Simas [mailto:dsimas@imageworks.com] > Sent: Tuesday, 17 April 2007 6:58 a.m. > To: ruby-talk ML > Subject: Re: factorial in ruby > > > On Tue, Apr 17, 2007 at 02:56:16AM +0900, Jason Roelofs wrote: > > No and most likely not. > > > > def fact(n) > > if n == 0 > > 1 > > else > > n * fact(n-1) > > end > > end > > For large enough n, this will overflow the stack. Since Ruby doesn't > optimize tail-recursive functions (and the above isn't tail recursive, > anyway), you'd better write this function as a loop (left as an exercise). > > DGS > > > > > Jason > > > > On 4/16/07, Trans wrote: > > > > > >Is factorial defined anywhere in Ruby's core or standard library. If > > >not will it be in 1.9+? > > > > > >Thanks, > > >T. > > > > > > > > > > > >