Time limit of a c program while calculating factorial of numbers in c [closed]

牧云@^-^@ 提交于 2019-12-25 19:42:05

问题


I am solving a problem on calculation of factorial and the challenge is as follows!

You are asked to calculate factorials of some small positive integers.

Input

An integer t, 1<=t<=100, denoting the number of testcases, followed by t lines,
each containing a single integer n, 1<=n<=100.

Output 

For each integer n given at input, display a line with the value of n!

My Code is giving me the correct solution but Time limit is exceeded which is 2 seconds:

The code is as follows:

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
void factorial(int N)
{
    printf("\n\n");
    int q,i,j,t,d,z;
    float p=0.0;
    for(i=2;i<=N;i++)
    p=p+log10(i);
    d=(int)p+1;//No of terms in the factorial
    int *b;
    //initialization of an array
    b=(int *)malloc(d*sizeof(int));
    b[0]=1;
    for(i=1;i<N;i++)
    b[i]=0;
    //calculation of factorial
    p=0.0;
    for(j=2;j<=N;j++)
    {
        q=0;
        p=p+log10(j);
        z=(int)p+1;
        for(i=0;i<N;i++)
        {
           t=(b[i]*j)+q;
           q=t/10;
           b[i]=t%10;   
        }
    }
    for(i=d-1;i>=0;i--)
    printf("%d",b[i]);

}
int main()
{
    int n,i,j;
    scanf("%d",&n);
    int *b;
    b=(int *)malloc(n*sizeof(int));
    for(i=0;i<n;i++)
    {
        scanf("%d",&b[i]);
    }
    for(i=0;i<n;i++)
    factorial(b[i]);
    return 0;
}

How can i make my program more efficient and produce the output in the given time limit? This challenge is from HackerEarth


回答1:


Since N is small, an efficient algorithm would be to pre-calculate all factorials:

BigNumberType fact[101];  // The numbers will become big, so you need (to create) a type to store it

fact[0] = 1.0;
for (i=0; i < 100; i++) {
  fact[i+1] = multiply(fact[i], i);
}

After that, looking up the value is trivial.

Note:

It may be even more efficient to scan the input vector for the highest number and only calculate factorials up to that number.



来源:https://stackoverflow.com/questions/16586842/time-limit-of-a-c-program-while-calculating-factorial-of-numbers-in-c

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