60分,#3和#5TLE

P1035 [NOIP2002 普及组] 级数求和

wzy20110830 @ 2024-02-21 18:06:03

#include <bits/stdc++.h>
using namespace std;
double s(int n)
{
    double k=0.0;
    for(int i=1;i<=n;i++)
        k+=1.0/(double)i;
    return k;
}
int main()
{
    int k,x=1;
    cin>>k;
    while(s(x)<=k)
        x++;
    cout<<x;
    return 0;
}

我就知道这种近似递归的写法会TLE,但是我不知道怎么优化,求大佬指点


by limaodadi @ 2024-02-21 18:18:14

#include <bits/stdc++.h>
using namespace std;
double m=0.0;
double s(int n)
{
    double k=m;
    k+=1/(double)n;
    m=k;
    return k;
}
int main()
{
    int k,x=1;
    cin>>k;
    while(s(x)<=k)
        x++;
    cout<<x;
    return 0;
}

每次s(x)的值之间只差1/x,咱可以吧s(x-1)的值记录下来,每次只用加1/x. @wzy20110830


by GG_and_go_to_died @ 2024-02-21 18:21:29

这个代码时间注定有问题 O(n \times k)过不了。 改成这样吧

#include <iostream>
using namespace std;

int main()
{
    ios::sync_with_stdio(false);
    int k,x=1;
    cin>>k;
    double sum=0.0;
    while (sum<=k) 
    {
        sum+=1.0/x;
        ++x;
    }
    cout<<x-1<<endl;
    return 0;
}

by jiejieya @ 2024-02-21 18:25:25

你每次调用函数都会从头算起,不如直接循环加,加到大于目标值就行了

#include<iostream>
using namespace std;
int main()
{
    double k = 0, i = 1,n = 0;
    cin >> n;
    for (i = 1; k <= n; i++)
        k += 1.0 / (double)i;
    cout << i - 1;
    return 0;
}

by wzy20110830 @ 2024-02-22 20:09:32

谢谢大佬们,方法有用,目前已AC


|