FCTRL2: Doubt in execution time

c
execution-time
time-limit

#1

#include <stdio.h>
#include <malloc.h>

void mult(int ,int* ,int );

int main()
{
 int a,i,b[200],k,l,d,c,x,temp;
 int *m;
 scanf("%d",&a);
 m = (int*) malloc (a*sizeof(int));
 for(i=0;i<a;i++)
 {
  scanf("%d",m+i);
 }
 for(i=0;i<a;i++)
 {
  k=0;
  l=*(m+i);
  while(l/10!=0)
  {
   b[k]= l%10;
   l=l/10;
   k++;
  }
  b[k] = l;
  for(d=*(m+i)-1;d>=1;d--)
  {
   temp=0;
   for(c=0;c<=k;c++)
   {
    x=b[c]*d+temp;
    b[c] = x%10;
    temp = x/10;
   }
   while(temp!=0)
   {
    b[++k]=temp%10;
    temp = temp/10;
   }
  }
  for(c=k;c>=0;c--)
  {
   printf("%d",b[c]);
  }
  printf("

",k);
}
return 0;
}

==============================================================================

#include <stdio.h>
#include <malloc.h>
 
void mult(int ,int* ,int );
 
int main()
{
 int a,i,b[200],k,l;
 int *m;
 scanf("%d",&a);
 m = (int*) malloc (a*sizeof(int));
 for(i=0;i<a;i++)
 {
  scanf("%d",m+i);
 }
 for(i=0;i<a;i++)
 {
  k=0;
  l=*(m+i);
  while(l/10!=0)
  {
   b[k]= l%10;
   l=l/10;
   k++;
  }
  b[k] = l;
  mult(*(m+i)-1,b,k);
 }
 return 0;
}
 
void mult(int i,int b[],int k)
{
 int c,temp=0,l=0,x;
 if(i!=1)
 {
  for(c=0;c<=k;c++)
  {
   x=b[c]*i+temp;
   b[c] = x%10;
   temp = x/10;
  }
  while(temp!=0)
  {
   b[++k]=temp%10;
   temp = temp/10;
  }
  mult(i-1,b,k);
 }
 else
 {
  for(c=k;c>=0;c--)
  {
   printf("%d",b[c]);
  }
  printf("

");
}
}

==============================================================================

In the above two codes the first code is executing perfectly but for the second one it is showing time limit exceeded. Why is that ? The logic I have used is same in both the cases.


#2

without running your programs, i think i’m able to see a big difference between each of them. you replaced a simple for loop (with an inner condition asserting an exit when d < 1) by a recursive function asserting an exit when i == 1. if (it may be possible or it may not be, i don’t know) i becomes < 1 for any reason (starting from 0, for instance), your recursive loop never ends, or actually ends when your i variable reaches 1 in an underflow (as you declared i as a signed int). maybe you can try to change the recursive function exit condition to the same as in your first code, meaning i < 1, not i == 1. hope it helps. i’ll have a look deeper if this trick doesn’t solve your problem. good luck :slight_smile: