您如何在C语言中编写阶乘? [英] How do you write factorial in C?

查看:81
本文介绍了您如何在C语言中编写阶乘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要输入该方程式,并且其中有一个阶乘.我想知道在C语言中是否存在* =乘法或pow(1,3)之类的东西.

I need to input this equation and there's a factorial in it. I would like to know if there was something like * = multiplication or pow(1,3) for factorial of something in C.

term = pow(-1, K) * pow(x, 2K)/(2K)

阶乘将用于最后2K.

推荐答案

很少需要一个用于计算阶乘的函数.因子增长得如此之快,以至于对于计算不会溢出的少数值,查找表就足够了.如果要循环计算项,则可以避免在整个项中使用累加器来计算阶乘.

Rarely you need a function for computing factorials. Factorials grow so fast that a look-up-table is sufficient for the few values for which the computation does not overflow. If you are computing terms in a loop, you can avoid computing the factorial using an accumulator for the entire term.

K = 0;
term = 1;

while (K<N) {

   /* use term */
   do_something_with(term);

   /* update term for new value of K */
   K += 1;
   term = -term * x*x / (2*K*(2*K-1));
}

如果这对您来说不清楚,则可以首先在显式累加器的地方派生此程序,然后将更新步骤组合到单个变量中,如上所述.该程序仍将存在阶乘计算爆炸的问题.

If that seems unclear to you, you can first derive this program where the accumulators are explicit, and then combine the update step into a single variable like above. This program will still have problems with the factorial computation blowing up.

K = 0;
pow_minus_1_K = 1;
pow_x_2K = 1;
factorial_2K = 1;

while (K<N) {

   /* compute term */
   term = pow_minus_1_K * pow_x_2K/factorial_2K;

   /* update accumulators for new value of K */
   K += 1;
   pow_minus_1_K = -pow_minus_1_K;
   pow_x_2K *= x*x;
   factorial_2K *= 2*K*(2*K-1);
}

这篇关于您如何在C语言中编写阶乘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆