Howto compute the factorial of x

前端 未结 7 1345
一生所求
一生所求 2020-12-20 00:05

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

Example: 5! 1x2x3x4x5 = 120.

相关标签:
7条回答
  • 2020-12-20 00:06

    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;
    
    }
    
    0 讨论(0)
  • 2020-12-20 00:07

    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.

    0 讨论(0)
  • 2020-12-20 00:09

    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?

    0 讨论(0)
  • 2020-12-20 00:13

    Try

    d = d * b;
    

    instead of

    d = d * a
    

    and it should work fine

    0 讨论(0)
  • 2020-12-20 00:14
    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;
    }
    
    0 讨论(0)
  • 2020-12-20 00:19

    You can simply do:

    for(b = 1; b <= a; b++) {
      d *= b;
    }
    // d now has a!
    
    0 讨论(0)
提交回复
热议问题