How can I compute double factorials in Perl?

拟墨画扇 提交于 2019-12-22 20:43:49

问题


Given Wikipedia's discussion of Double Factorials, can anyone suggest where I might find a bignum version of this for Perl, or else suggest how it might be written?


回答1:


Perl will handle whatever your C compiler can handle, for anything bigger you should be using Math::BigInt.

I would recommend you read perlnumber.

A definition for the double factorial (in perl golf):

sub f{$_[0]&&$_[0]>=2?$_[0]*f($_[0]-2):1}



回答2:


Here are lots of alternative approaches to implementing Fast Factorial Functions. The Poor Man's algorithm may be a good choice for you, as it uses no Big-Integer library and can be easily implemented in any computer language and is even fast up to 10000!.

The translation into Perl is left as an exercise for the OP :-)




回答3:


Perl 5.8 and later come with the bignum package. Just use it your script and it takes care of the rest:

use bignum;

I talk about this a bit in Mastering Perl when I use the factorial in the "Profiling" chapter.




回答4:


Although dsm's answer is accurate, the real way to calculate factorials in Perl, regardless of whether you use dsm's algorithm (golfed or not) is to memoize it. If you are going to call it with any frequency, you'll want to memoize any recursive mathematical function.

use Memoize;
memoize( 'fact2' );

sub fact2 {$_[0]&&$_[0]>=2?$_[0]*fact2($_[0]-2):1}



回答5:


If you're doing floating point calculations with (double) factorials, you can quickly get into overflow or underflow situations. It's usually best to work with logarithms. Adding and subtracting logarithms of factorials then taking the exponential at the end is more reliable than multiplying and dividing factorials directly. More details here.



来源:https://stackoverflow.com/questions/416377/how-can-i-compute-double-factorials-in-perl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!