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

时间:2016-07-16 10:50:31

标签: c++ exception-handling

如果n或p 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;
            }
        }
    }
}

4 个答案:

答案 0 :(得分:0)

Calculator::power是无限递归的:它使用它收到的相同参数调用自身。当然某处 ...; - ]

应该有乘法

答案 1 :(得分:0)

超出时间限制是在一段时间后没有输出时产生的错误,在你的情况下你有一个无限递归你调用电源(a,b) 如果a> 0&amp;&amp; b> 0然后你调用power(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);}

答案 2 :(得分:0)

这是因为您的代码中有无限递归。

请看这篇文章:

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

答案 3 :(得分:0)

您的代码几乎是正确的。只是一个小案件处理不当。在计算数字的幂时,您再次以相同的参数递归地调用相同的函数。这里没有提供基本案例,因此您的功能不知道何时停止。您可以执行以下更改:

在函数中使用基本案例:     if(p == 0)     返回1;

并以递归的方式递归调用您的函数:     返回(N *(功率(N,P-1)));

您的问题很容易解决。