Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you implement the factorial function in C++? [duplicate]

Possible Duplicates:
Calculating large factorials in C++
Howto compute the factorial of x

How do you implement the factorial function in C++? And by this I mean properly implement it using whatever argument checking and error handling logic is appropriate for a general purpose math library in C++.

like image 783
Jonathan Allen Avatar asked Apr 19 '11 19:04

Jonathan Allen


People also ask

What is the formula for factorial in C?

Algorithm of Factorial Program in C Read the integer and assign it to a variable. From the value of the integer up to 1, multiply each digit and update the final value. The final value at the end of all the multiplication till 1 is the factorial.

Is there a function for factorial in C?

Although there is no C function defined specifically for computing factorials, C math library lets you compute gamma function.


2 Answers

Recursive:

unsigned int factorial(unsigned int n) 
{
    if (n == 0)
       return 1;
    return n * factorial(n - 1);
}

Iterative:

unsigned int iter_factorial(unsigned int n)
{
    unsigned int ret = 1;
    for(unsigned int i = 1; i <= n; ++i)
        ret *= i;
    return ret;
}

Compile time:

template <int N>
struct Factorial 
{
    enum { value = N * Factorial<N - 1>::value };
};

template <>
struct Factorial<0> 
{
    enum { value = 1 };
};

void foo()
{
    int x = Factorial<4>::value; // == 24
    int y = Factorial<0>::value; // == 1
}
like image 75
Hovhannes Grigoryan Avatar answered Oct 13 '22 14:10

Hovhannes Grigoryan


Besides the obvious loops and recursions, modern C++ compilers support the gamma function as tgamma(), closely related to factorial:

#include <iostream>
#include <cmath>
int main()
{
    int n;
    std::cin >> n;
    std::cout << std::tgamma(n+1) << '\n';
}

test run: https://ideone.com/TiUQ3

like image 40
Cubbi Avatar answered Oct 13 '22 15:10

Cubbi