C ++程序计算大阶乘的商 [英] C++ program to calculate quotients of large factorials
问题描述
我如何编写一个c ++程序来计算大阶乘。
How can I write a c++ program to calculate large factorials.
例如,如果我想计算(100!)/答案是100,但如果我分别计算分子和分母的阶乘,这两个数字是巨大的。
Example, if I want to calculate (100!) / (99!), we know the answer is 100, but if i calculate the factorials of the numerator and denominator individually, both the numbers are gigantically large.
推荐答案
Dirk的答案(其中imo是正确的答案):
expanding on Dirk's answer (which imo is the correct one):
#include "math.h"
#include "stdio.h"
int main(){
printf("%lf\n", (100.0/99.0) * exp(lgamma(100)-lgamma(99)) );
}
尝试,它真的做你想要的,即使它看起来有点疯狂,如果你不熟悉它。使用bigint库将是非常低效的。拍摄日志的速度是超快的。这运行瞬间。
try it, it really does what you want even though it looks a little crazy if you are not familiar with it. Using a bigint library is going to be wildly inefficient. Taking exps of logs of gammas is super fast. This runs instantly.
您需要乘以100/99的原因是gamma等于n-1!不是n!所以是的,你可以只做exp(lgamma(101)-lgamma(100))。此外,gamma定义的不仅仅是整数。
The reason you need to multiply by 100/99 is that gamma is equivalent to n-1! not n!. So yeah, you could just do exp(lgamma(101)-lgamma(100)) instead. Also, gamma is defined for more than just integers.
这篇关于C ++程序计算大阶乘的商的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!