zoukankan      html  css  js  c++  java
  • Harmonic number

    Description
    In mathematics, the nth harmonic number is the sum of the reciprocals of the first n natural numbers:
    
    h[n] = 1 + 1/2 + 1/3 + ……+1/n;
    
    In this problem, you are given n, you have to find Hn.
    
    Input
    Input starts with an integer T (≤ 10000), denoting the number of test cases.
    
    Each case starts with a line containing an integer n (1 ≤ n ≤ 108).
    
    Output
    For each case, print the case number and the nth harmonic number. Errors less than 10-8 will be ignored.
    
    Sample Input
    12
    1
    2
    3
    4
    5
    6
    7
    8
    9
    90000000
    99999999
    100000000
    Sample Output
    Case 1: 1
    Case 2: 1.5
    Case 3: 1.8333333333
    Case 4: 2.0833333333
    Case 5: 2.2833333333
    Case 6: 2.450
    Case 7: 2.5928571429
    Case 8: 2.7178571429
    Case 9: 2.8289682540
    Case 10: 18.8925358988
    Case 11: 18.9978964039
    Case 12: 18.9978964139
    #include <iostream>
    #include <cstdio>
    #include <cmath>
    using namespace std;
    const double r=0.57721566490153286060651209;     //欧拉常数
    double a[10000];
    
    int main()
    {
        a[1]=1;
        for (int i=2;i<10000;i++)
        {
            a[i]=a[i-1]+1.0/i;
        }
        int n;
        cin>>n;
        for (int kase=1;kase<=n;kase++)
        {
            int n;
            cin>>n;
            if (n<10000)
            {
                printf("Case %d: %.10lf
    ",kase,a[n]);
            }
            else
            {
                double a=log(n)+r+1.0/(2*n);
                ///double a=log(n+1)+r;
                printf("Case %d: %.10lf
    ",kase,a);
            }
        }
        return 0;
    }

    前面10000个可以正常打表,后面的我们就用公式,再说了,这个公式能成立,本来就是在n比较大的时候,公式如下:  r为常数,r=0.57721566490153286060651209(r就是欧拉常数)。

    特别注意,由于题目要求精度为10^-8,常数r也是前人推导出来的,然而也只推导了有限位数,所以正常利用这个公式,并不能达到精度要求,我们只好比较样例和我们自己输出的数据,增添一些可行的项,经尝试,在原公式的基础上,再减去一个1.0/(2*n)恰好可以满足精度

  • 相关阅读:
    测试小技巧之常用工具
    测试小技巧之浏览器插件
    可变参数列表
    对象属性和数组元素的初始默认值
    静态块(变量)和非静态块(变量)
    类初始化顺序
    基本类型的重载规则
    构造器访问权限控制
    MySQL Server架构图
    递归与非递归实现树的遍历(java)
  • 原文地址:https://www.cnblogs.com/biu-biu-biu-/p/5737328.html
Copyright © 2011-2022 走看看