【问题标题】:Regarding time out in code关于代码超时
【发布时间】:2023-03-04 13:10:01
【问题描述】:
  for(int a0 = 0; a0 < t; a0++){
    long long int n;
 //taking the input limit
    cin >> n;
    long long int  n1=8,n2=34,sum=10;
    //iteration till the limit
    while(n2<=n)
    {
        long long int l=n2;
      //for finding the next even fibonacci number
        n2=4*(n2)+n1;
        n1=l;
        sum+=n1;
    }
    cout<<sum<<endl;
}

这是在给定限制 n 的情况下求偶数斐波那契数之和的代码。 当我使用 int 代替 long long int 时出现超时问题。处理不同的数据类型有区别吗?性能会有怎样的变化?

【问题讨论】:

  • 你很可能会溢出int,因此永远不会跳出循环。
  • 请提供n的测试值
  • 你能解释一下吗??溢出时会发生什么?

标签: c++ arrays performance


【解决方案1】:

您不需要使 n2=34。 我们可以用数组来完成这个问题,像这样:

int a[1001];
memset(a,0,sizeof(a));
while(!EOF){
    a[0]=a[1]=1;
    cin>>n;
    for(int i=2;i<=n;i++){
        a[i]=a[i-1]+a[i-2];
    }
    cout<<a[n];
}

【讨论】:

  • 我只需要斐波那契数。所以我推导出了这个公式。如果 n 值非常大,可能会产生存储问题。所以我没有使用数组。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-17
  • 1970-01-01
  • 2012-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多