C program for calculating factorial

Viewed 587

i have written a small function which calculates factorial for a number in C as follows:

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

I call the function shown above as:

factNnumbers(takeInputN());

where the function to take the input (takeInputN) is defined as:

int takeInputN()
{   
    int n;
    printf("\n\nHow many numbers ?? \n ");
    scanf("%d", &n);
    return n;
}

If I change one line in my factorial code as shown below , my program works perfectly. Otherwise with the above code it prints the factorial of the number input -1 (example if number input is 5, it will print the factorial of 4). Why is this happening?.

int factNnumbers(int n)
{
    if(n != 1)
        return (n * factNnumbers(--n));
}
6 Answers

I think it’s better to use the tgamma function from math.h for double precision calculations involving factorials (such as Poisson distribution etc.): tgamma(n+1) will give you factorial(n).

Factorial function is increasing very fast, and this will work also for values too big to fit an integer type.

Related