时间限制超出错误C++编译

Time Limited Exceeded error C++ compile

本文关键字:错误 C++ 编译 出错 时间      更新时间:2023-10-16

如果n或p<0作为以下代码。但在codechef中编译时,我遇到了一个Time Limited Exceeded错误
问题:
1.当C++中发生Time Limited Exceeded错误时
2.我的代码哪出了问题?

#include <cmath>
#include <iostream>
#include <exception>
#include <stdexcept>
#include <cstdio>
using namespace std;
class Calculator{
public:
    int power(int n,int p){
        if(n<0 || p < 0)
            throw "n and p should be non-negative";
        else
           return power(n,p);
    }
};
int main()
{
    Calculator myCalculator=Calculator();
    int T,n,p;
    cin>>T;
    while(T-->0){
        if(scanf("%d %d",&n,&p)==2){
            try{
                int ans=myCalculator.power(n,p);
                cout<<ans<<endl; 
            }
            catch(exception& e){
                cout<<e.what()<<endl;
            }
        }
    }
}

之所以会发生这种情况,是因为代码中有无限递归。

看看这篇文章:

int power(int n,int p){
    if(n<0 || p < 0)
        throw "n and p should be non-negative";
    else
       return power(n,p);
}

它将无限次调用power(n, p),因为您没有退出执行的条件。所以你只需要把一个又一个函数调用放在堆栈上。你甚至不做任何计算!

你需要这样的退出条件:

int power(int n,int p){
    if(n<0 || p < 0)
        throw "n and p should be non-negative";
    else if (p == 0)
    {
        return 1;
    }
    return n*power(n,p-1);
}

Calculator::power是无限递归的:它使用与接收到的参数相同的参数调用自己。肯定应该有乘法在那里某处…;-]

超过时间限制是一个错误,当在一定时间后没有生成输出时,在您的情况下,您有一个称为幂(a,b)的无限递归如果a>0&amp;b>0,然后调用幂(a,b),从而进入无限递归尝试添加此

int power(int n, int p){ if(n<0 || p < 0) throw "n and p should be non-negative";
else if (p == 1) return 1;
else return n*(n,p-1);}

您的代码几乎是正确的。只是一个小案子处理不当。在计算一个数字的幂时,您已经用相同的参数再次递归调用了相同的函数。这里没有提供基本情况,因此您的函数不知道何时停止。你可以做一些这样的改变:

在函数中使用基本情况:如果(p==0)返回1;

并用欺骗的力量递归调用您的函数:return(n*(幂(n,p-1));

你的问题很容易解决。