Harmonic Number LightOJ - 1234(暴力分段打表 / 欧拉爷爷的O(1))

Harmonic Number LightOJ - 1234

题意:

给你一个调和级数。
f ( n ) = 1 + 1 2 + 1 3 + 1 4 + 1 5 + . . . + 1 n f(n)=1+\frac{1}{2}+\frac{1}{3}+\frac{1}{4}+\frac{1}{5}+...+\frac{1}{n} f(n)=1+21+31+41+51+...+n1
要求你求出来。n到达1e8

思路1:

  1. 假如直接暴力的话,时间肯定允许,但是内存肯定MLE。
  2. 所以可以分段进行打表。

反思1

本题让我学到了 printf(“%.f ”)。f可以代表double也可以float。

AC1

#include <iostream>
#include <cstdio>
#define For(i,x,y) for(int i=(x); i<=(y); i++)
#define fori(i,x,y) for(int i=(x); i<(y); i++)
using namespace std;
const int N = 1e8+10;
const int maxn = 1e6+10;
double ha[maxn];
void table(){
    double res = 0;
    fori(i,1,N){
        res += 1.0/i;
        if(i%100==0) ha[i/100] = res;
    }
}
int main()
{
    //ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
    table();
    int tt, kase = 0; scanf("%d", &tt);
    while(tt--){
        double ans = 0;
        int n; scanf("%d", &n);
        int st = n/100;
        ans = ha[st];
        For(i,st*100+1,n){
            ans += 1.0/i;
        }
        printf("Case %d: %.8f\n", ++kase, ans);
    }
    return 0;
}

思路2:

  1. 欧拉爷爷,提出了一个解法。提供了一个欧拉常数
  2. C = 0.57721566490153286060651209(111
  3. f ( n ) = c + l n ( n ) + 1 2 n f(n)=c+ln(n)+\frac{1}{2n} f(n)=c+ln(n)+2n1

AC2

#include <iostream>
#include <cstdio>
#include <math.h>//<math.h>
#define For(i,x,y) for(int i=(x); i<=(y); i++)
#define fori(i,x,y) for(int i=(x); i<(y); i++)
using namespace std;
const double c  = 0.57721566490153286060651209;
const int maxn = 1e5+10;
double ha[maxn];
void table(){
    double res = 0;
    fori(i,1,maxn){
        res += 1.0/i;
        ha[i] = res;
    }
}
int main()
{
    int tt, kase = 0; scanf("%d", &tt);
    table();
    while(tt--){
        int n; scanf("%d", &n);
        double ans = 0;
        if(n<maxn) ans = ha[n];//For(i,1,n) ans += 1.0/i;
        else ans = c + log(n) + 1.0/(2*n);
        printf("Case %d: %.10f\n", ++kase, ans);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值