LightOJ 1234 - Harmonic Number

// Harmonic Series
// 1 + 1/2 + 1/3 + ... + 1/n;
// Find the nth sum of Harmonic numbers

#include<bits/stdc++.h>

//#include<cstdio>
//#include<iostream>
//#include<algorithm>
//#include<vector>
//#include<cstring>
//#include<cmath>
//#include<map>

using namespace std;

#define fast ios_base::sync_with_stdio(false)
#define bfast cin.tie(0)
#define outs(x) cout << x << " "
#define outn(x) cout << x << "\n"
#define sf scanf
#define pf printf
#define nl puts("")
#define psb push_back
//#define i64 long long
#define high 1000000
#define EulerGamma 0.57721566490153286060651209;

typedef long long LL;
typedef vector<int>vii;
typedef vector<LL>vll;

double ar[high];

void harmonic()
{
    int i;

    ar[1] = 1.0;
    ar[2] = ar[1] + 0.5;

    for(i=3; i<=high; i++)
    {
        ar[i] = (ar[i-1] + (1.0 / (double(i)))) * 1.0;
    }

    //for(i=1; i<=10; i++) cout << ar[i] << "; ";
}

int main()
{
    harmonic();
    int t, tc=0 , n;
    double ans=0.0;
    sf("%d", &t);
    while(t--)
    {
        sf("%d", &n);

        if(n <= high)
        {
            ans = ar[n];
        }

        else
        {
            ans = log(n + 0.5) + EulerGamma ; // EulerGamma = Euler-Mascheroni Constant. It is defined as the limiting difference between the harmonic series and the natural logarithm
        }

        pf("Case %d: %.10lf\n", ++tc, ans);
    }

    return 0;
}

Comments

Popular posts from this blog

SPOJ-CMG - Collecting Mango

LightOJ 1009 - Back to Underworld

LeetCode Palindrome Number