In the following question I am getting time limit exceeded message on whichever compiler I tried(though they were all online compilers).What should be the problem?
#include <stdio.h>
int fact(int);
int main(void)
{
int num,res;
printf("enter any number");
scanf("%d",&num);
res=fact(num);
printf("%d",res);
return 0;
}
int fact(int x)
{
int ans;
while(x!=1)
ans=(x*fact(x-1));
return ans;
}
Problem is that your fact
function never stopped since while
loop never ends.
int fact(int x)
{
int ans;
while(x!=1)
ans=(x*fact(x-1)); //X is never changed!
return ans;
}
Probably you wanted this:
int fact(int x)
{
int ans = 1; //Set default value for return
if(x!=1) //Go recursive only if X != 1
ans=(x*fact(x-1));
return ans;
}
It is because your fact function goes into infinite loop.
Assuming you are calculating factorial of a number x, this should be the correct fact function.
int fact(int x)
{
if(x!=1)
return x*fact(x-1);
return 1;
}
int fact(int x)
{
int ans;
while(x!=1)
ans=(x*fact(x-1));
return ans;
}
It is an infinite loop. This is the reason why you get an error as time limit exceeded. Replace the loop to an if condition:
int fact(int x)
{
int ans = 1;
if(x!=1)
ans=(x*fact(x-1));
return ans;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.