Howto compute the factorial of x

柔情痞子 提交于 2019-11-29 12:39:31

how to get the som of an integer x, indicated by x!, is the product of the numbers 1 to x.

Did you mean factorial of x ?

Change d = d*a; to d = d*b inside the loop

You can simply do:

for(b = 1; b <= a; b++) {
  d *= b;
}
// d now has a!

This is the optimal implementation in size and speed:

int factorial(int x)
{
    static const int f[13] = { 1, 1, 2, 6, 24, 120, /* ... */ };
    if ((unsigned)x < (sizeof f/sizeof f[0])) return f[x];
    else return INT_MAX+1; /* or your favorite undefined behavior */
}

Hint: x! (x factorial) does not fit in an int except for very very small values of x.

Try

d = d * b;

instead of

d = d * a

and it should work fine

You actually have a lot of redundant code there, that might be why you did not spot the error yourself.

To calculate the factorial, you only need the accumulator (d in the above code) and the input (a). Why?

My code is not good as other but it works for me:

#include <iostream>
using namespace std;

unsigned int fattoriale (int n){
    if (n == 1){
        return 1;
    }
    else {
        return n * fattoriale(n-1);
    }
}

int main() {
    int tmp, num;
    cin >> num;

    tmp = fattoriale(num);

    cout << "Stampo il fattoriale del numero inserito: " << tmp << endl;

}
Umair Zia
int factorial(int x)
{
    int f;
    if (x == 0)
    {
        f = 1;
    }
    else if (x > 0)
    {
     f = x*factorial(x-1);
    }
    return f;
}

int main()
{
   int n = 0;
   cout << factorial(n);

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