Wrong answer in "CHEFCAKES"

question:

#include<iostream>
#include<math.h>
using namespace std;
long long int fact(long long int num)
{
    if(num==2)
    {
        return 2;
    }
    return fact(num-1)*num;

}
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        long long int i,n,temp,sum=0,ans=0;
        cin>>n; 
        long long int a[n];       
        for(i=0;i<n;i++)
        {
            cin>>a[i];
            sum=sum+a[i];
        }
        temp=fact(n-1)*(sum);
        ans=((pow(10,n))-1)/9;
        ans=ans*temp;
        cout<<ans<<endl;

    }
}
it is showing tle

Yes you will get TLE because of using recursion for calculating factorial for every testcases , you should preprocess the factorial in an Array.

1 Like

it’s giving TLE because if (n<=2)then fact(n-1)will not terminate so u have to write
if((n==0)|(n==1)) return 1,this base case should be added .

1 Like

Thanks a lot!

:+1: :+1:

ur welcome :slightly_smiling_face: