老是TLE,求大佬指点!

P1035 [NOIP2002 普及组] 级数求和

QFMYMIYI @ 2020-02-12 12:52:20

#include <stdio.h>
int main(void)
{
    int n,k;
    float sn=0;
    scanf("%d",&k);
    {
        for(n=1;sn<k;n++)
        {
            sn=sn+1/n;
        }
        printf("%d",n);
    }
    return 0;
}

求解,老是TLE,感觉已经是我最简单的算法了啊。。。


by infinities @ 2020-02-12 12:55:26

@QFMYMIYI sn+1/n 应该改成sn+1.0/n


by long_long @ 2020-02-12 13:09:58

sn+1.0/n


by QFMYMIYI @ 2020-02-12 13:13:42

@装弱是种美德 那就WA了


by QFMYMIYI @ 2020-02-12 13:14:46

@long_long WA了


by schtonn @ 2020-02-12 13:30:42

#include<cstdio>
#include<cmath>
const double gamma=0.5772156649;
int main() {
    int k,n;
    scanf("%d",&k);
    n=exp(k-gamma)+0.5;
    printf("%d",n);
    return 0;
}

by infinities @ 2020-02-12 14:42:31

@QFMYMIYI sn<k改成sn<=k


by QFMYMIYI @ 2020-02-12 20:23:10

#include <stdio.h>
int main(void)
{
    int n,k;
    double sn=0;
    scanf("%d",&k);
    {
        for(n=1;sn<k;n++)
        {
            sn=sn+1.0/n;
            if(sn>k)
                break;
        }
        printf("%d",n);
    }
    return 0;
}

自己解决了。


|