views:

109

answers:

5

Please suggest me a more efficient alternative to go about this Program

#include <stdio.h>

int main(void)
{
    int k, i, t;
    int arr[100]; //Declaring an array

    printf("Enter a positive integer: ");
    scanf("%d", &k);

    for (i = 0; i < k; i++)
    {
        //printf("enter a value %d : ", i);
        scanf("%d", &arr[i]);
    }

    for (i = 0; i < k; i++)
    {
        fact(arr[i]);
    }

}

int fact(int num) // defining function fact(Num)
{

    int i;
    int fact1 = 1;

    for (i = 1; i <= num; i++)
    {
        fact1 = fact1 * i;
    }

    printf("%ld\n", fact1);

}
A: 

You can use Stirling's approximation to calculate the factorial for large numbers.

Gangadhar
For the domain relevant to a C `int` (i.e., n<20), Stirling's approximation appears to have pretty significant error. Why would you not just use integer arithmetic, or a lookup table?
Ken
A: 

This has been answered before here

bramp
A: 

You can use Stirling's formula as an approximation for large factorials. If very large exact factorials are needed, you'll need to use bignum arithmetic. The asymptotically-best efficiency is obtained by computing n! from its prime factorization. For more algorithms, check this

Yassin
A: 

See the Fast Factorial Functions website and to the Computation section of the Factorial Wikipedia article.

Alexander
+3  A: 

For small arguments, I agree with Hamish Grubijan's comment: just tabulate the values and look 'em up at run time. There aren't that many values for which n! is representable in a machine number, so you could tabulate them all.

The logarithm of n! is often more useful. It will fit inside a machine number when n! itself would overflow. See How to compute log factorial.

John D. Cook