php算阶乘(即n!)(非递归版)
发布时间:2014-06-20 22:12:12 来源:51推一把
【摘要】递归版算法请到这个网址查看:http://hi.baidu.com/liclny/blog/item/54c22f0855e8ab36e82488a1.html更好的递归版算法请查看:http://www.phpchina.com/bbs/thread-14503-1-1.html延伸阅读-PHP排列组合纯算法实现 (31楼cator的算法):http://bbs.phpchina.com/thread
递归版算法请到这个网址查看:http://hi.baidu.com/liclny/blog/item/54c22f0855e8ab36e82488a1.html
更好的递归版算法请查看:http://www.phpchina.com/bbs/thread-14503-1-1.html
延伸阅读-PHP排列组合纯算法实现 (31楼cator的算法):http://bbs.phpchina.com/thread-180756-4-1.html
=========================
/**
* 阶乘方法(非递归)
* bcmul用法曾经参考过以下文章,在此致谢:
* - http://www.phpchina.com/bbs/thread-14503-1-1.html
*
* @param integer $s 大于0的整数
*/
function factorial( $s ){
$s = (int)$s;
if ($s <= 0 ){
trigger_error(Factorial Error! Argument must be larger than 0!, 256);
}
$result = 1;
for( $i = $s ; $i > 1 ; $i-- ){
//大数阶乘问题,应该用bcmul,所以不用“$result = $result * $i;”。不过如果没搞那么复杂的大数,用*效率也许会高一点
$result = bcmul($result, $i);
}
return $result;
}
更好的递归版算法请查看:http://www.phpchina.com/bbs/thread-14503-1-1.html
延伸阅读-PHP排列组合纯算法实现 (31楼cator的算法):http://bbs.phpchina.com/thread-180756-4-1.html
=========================
/**
* 阶乘方法(非递归)
* bcmul用法曾经参考过以下文章,在此致谢:
* - http://www.phpchina.com/bbs/thread-14503-1-1.html
*
* @param integer $s 大于0的整数
*/
function factorial( $s ){
$s = (int)$s;
if ($s <= 0 ){
trigger_error(Factorial Error! Argument must be larger than 0!, 256);
}
$result = 1;
for( $i = $s ; $i > 1 ; $i-- ){
//大数阶乘问题,应该用bcmul,所以不用“$result = $result * $i;”。不过如果没搞那么复杂的大数,用*效率也许会高一点
$result = bcmul($result, $i);
}
return $result;
}