为什么超出时限?

时间:2021-01-30 18:09:25

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;
}

3 个解决方案

#1


4  

Problem is that your fact function never stopped since while loop never ends.

问题是你的事实函数从未停止过,因为while循环永远不会结束。

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;
}

#2


1  

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.

假设您正在计算数x的阶乘,这应该是正确的事实函数。

int fact(int x)
{
    if(x!=1)
        return x*fact(x-1);
    return 1;
}

#3


0  

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:

这是一个无限循环。这就是超出时间限制时出错的原因。将循环替换为if条件:

int fact(int x)
{
    int ans = 1;
    if(x!=1)
        ans=(x*fact(x-1));
    return ans;
}

#1


4  

Problem is that your fact function never stopped since while loop never ends.

问题是你的事实函数从未停止过,因为while循环永远不会结束。

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;
}

#2


1  

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.

假设您正在计算数x的阶乘,这应该是正确的事实函数。

int fact(int x)
{
    if(x!=1)
        return x*fact(x-1);
    return 1;
}

#3


0  

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:

这是一个无限循环。这就是超出时间限制时出错的原因。将循环替换为if条件:

int fact(int x)
{
    int ans = 1;
    if(x!=1)
        ans=(x*fact(x-1));
    return ans;
}