Time limit exceeded

Plz see this for question.

//The code is giving timing errors: Time limit (1s) exceeded.

//Plz help on how I can make my code faster.


#include <stdio.h>

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

int main()
{
    int n, i, tcs, j, l, m;
    long long count, y=((10^9)+7), k;
    scanf("%d", &tcs);
    int fact[tcs];
    int arr[tcs];

    for(j=0; j<tcs; j++)
    {
        scanf("%d", &arr[j]);
    }

    j=0;
    for(m=0; m<tcs; m++)
    {
        fact[m]=calc_fact(arr[j]);
        j++;
    }

    m=0;
    for(l=0; l<tcs; l++)
    {
        i=1;
        count=0;
        while(i<=fact[m])
        {
            if((fact[m])%i==0)
            count++;
            i++;
        }

        m++;
        k=count%y;
        printf("%lld\n", k);
    }
    return 0;

}

Here’s my answer
First for calculating factorial you could use an iterative approach i.e., assign fact[0]=1; for(i=1;i<=n;++i) fact[i]=fact[i-1];
Also i believe that fact[tcs] may be larger than your int range and hence will give wrong answers.

For this question I believe there are many other easy approaches.

Your code is not an efficient code .Its following recurrsive method.
Intead of using this method you must use bottom up approach.Compute the factorial of a lower number store it somewhere(ex matrix) then use it to compute higher factorial.
ex factorial 3=(factorial 2)*3 in which yo have already calculated factorial 2.

You cannot use long long y=((10^9)+7);

In this statement,
y=((3)+7)
y=10

But it should be 1000000007.

Because ^ is an EXOR operator, it will EXOR 10 & 9 to give 3.

This will not prevent your code from giving timing error.
But this mistake will definitely give you Wrong Answer if there will be no time limit restriction.

@pankaj_chopra thanks…

1 Like
//