memory issue in FCTRL2

I wrote the following code:

#include<stdio.h>
int main()
{
    int t,a[5],i,fact=1,p;
    scanf("%d",&t);
    for(i=1;i<=t;i++)
    {
        scanf("%d",&a[i]);
    }
    for(i=1;i<=t;i++)
    {


        while(a[i]>=1)
        {
            fact=fact*a[i];
            a[i]--;

        }
        printf("\n%d",fact);
        fact=1;
    }
    return 0;
}

the website said “Runtime Error Your code compiled and ran but encountered an error. The most common reasons are using too much memory or dividing by zero. For the specific error codes see the help section.”

while
this code has been accepted :

#include<stdio.h>
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int remi=0,mult,a[200]={0},i,j,m=1,n;
        scanf("%d",&n);
        a[1]=1;
        for(i=1;i<=n;i++)
        {
           for(j=1;j<=m;j++)
            {
                mult=a[j]*i;
                mult+=remi;
                a[j]=mult%10;
                remi=mult/10;
            }
            if(remi>0)
            {
                while(remi)
                {
                a[++m]=remi%10;
                remi/=10;
                }
            }
        }
        for(i=m;i>=1;i--)
        {
            printf("%d",a[i]);
        }
        printf("\n");
    }
    return 0;
}  

I think , I have used less memory than this code.
Please help!!

Run time errors are also due to accessing array index out of its bound.

you have array a of size 5, so its index are a[0…4], if you try to access a[5 or more] you will get a segmentation fault (run error)

You can declare few arrays of size 10^6 without having to worry about memory limit, 1526MB is the max memory limit i believe.

If you declare too much memory (or use too much memory) you get a stack overflow error not a segmentation fault.

PS: please format your code so it is readable. Thanks.

1 Like

Look at the constraints section. Value of t can be from 1 to 100, and then you allotting array only 5 spaces will backfire.

And your code will anyway give a WA. Because n can be upto 100, and 100 factorial CANNOT be stored in any data type in C/C++ , even long long int backfires there.

That guy used a very clever way, a standard method to compute big numbers in C++. I recommend that you solve this Q in python, because the way python handles large numbers, your similar code will get AC.