当输入为14,无法得到标准输出675214,显示为tle,为啥?如何改正该代码

P1035 [NOIP2002 普及组] 级数求和

tianyang @ 2020-03-04 23:50:59

#include<bits/stdc++.h>
using namespace std;
double Sn(int n);
int main()
{
    int k,n=1;
    cin>>k;
    while(Sn(n)<=k)
    {
        n++;
    }
    cout<<n;
    return 0;
}
double Sn(int n)
{
    if(n==1)
    return 1.00;
    else
    return 1.00/n + Sn(n-1);
}//(14,675214) 

by S1nner @ 2020-03-04 23:53:35

@tianyang 你的复杂度是 O(N^2)


by ztxtjz @ 2020-03-04 23:54:26

可以把每次Sn的值记录下来


by ztxtjz @ 2020-03-04 23:54:46

考虑一个for循环解决呗


by tianyang @ 2020-03-05 10:26:50

懂了,谢啦各位


by 湾水 @ 2020-09-07 07:11:15

弱弱问一句:输入14 我输出675214 --```cpp

include <iostream>

using namespace std; int main() { float sum = 0; int i = 1, k; cin >> k; for (i = 1; i <= 1000000; ++i) { sum += (float)1 / i; if (sum > k) { cout << i; return 0; } } return 0; }



哪不对了呢

|