[SOLVED] Sum of 1 + 1/2 + 1/3 +…. + 1/n without iterations using digamma function and Euler's constant


So i like to make my life hard, i’ve got a task to calculate the sum of
1 + 1/2 + 1/3 + 1/4 +.... + 1/n.
The conditions is to not use iterations but a closed formula. On this post : https://math.stackexchange.com/questions/3367037/sum-of-1-1-2-1-3-1-n

I’ve found a pretty neat looking solution: 1+1/2+1/3+⋯+1/n=γ+ψ(n+1)
where γ is Euler’s constant and ψ is the digamma function.

For digamma I’m using the boost c++ libraries and I calculate the Euler’s constant using exp(1.0).

The problem is that I don’t get the right answer. Here is my code:

#include <iostream>
#include <cmath>
#include <boost/math/special_functions/digamma.hpp>

int main(){
int x; 
const double g = std::exp(1.0);

std::cin >> x;

std::cout<<g + boost::math::digamma(x+1);

return 0;

Thanks in advance) !


Euler is known for having a lot of things named for him.

That can easily become confusing, as seems to be case here.

What you are adding to the digamma function result is Euler’s number. You are supposed to add Euler’s constant, which is a different number named after Euler.

You can find the correct number in boost as boost::math::constants::euler, e.g.:

const double g = boost::math::constants::euler<double>();

(Thanks @Eljay)

For some context on such how much is named after Leonhard Euler and how confusing it can get, here is the Wikipedia page’s section on just numbers named after him, counting 11 different items: https://en.wikipedia.org/wiki/List_of_things_named_after_Leonhard_Euler#Numbers

Answered By – user17732522

Answer Checked By – Willingham (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.