Harmonic Series optimization

Copyright: For reprint, whisper bloggers https://blog.csdn.net/lylzsx20172018/article/details/90736370

The concept of harmonic series : n / 1 + n / 2

Normal thinking :

long long H( int n ) {
    long long res = 0;
    for( int i = 1; i <= n; i++ )
        res = res + n / i;
    return res;
}

If n (1 ≤ n <231), the above code will timeout

Optimization process :

  1. First determined before sqrt (n) and items: i.e., n / 1 + n / 2 + ... + n / sqrt (n)

    long long m=sqrt(n), ans=0;
     for(i=1; i<=m; i++)
     ans+=(n/i);
    
  2. And then find all the items back

 long long m=sqrt(n), ans=0;
   for(i=1; i<=m; i++)
   ans+=i*(n/i-n/(i+1));

Analysis: performing step (2), the value of each one of less than or equal sqrt (n), the calculated value of the number of items 1 to sqrt (n) multiplied by its key value to quickly answer

For example :

10 = n-
sqrt (10) = 3
to obtain its first three and 10/10 + 1/2 + 10/3, then seek back

Item 1 is: Number: 10 / 1-10 / 2, respectively: 10 / 10,10 / 9,10 / 8,10 / 7,10 / 6
term value of 2: Number: 10/2 -10/3 are: 10 / 5,10 / 4
item value of 3: number: 10 / 3-10 / 4 are: sqrt (10)

Note: When n / (int) sqrt (n) == (int) sqrt (n), the value is sqrt (n) will be calculated twice

Complete code :

        long long m=sqrt(n),ans=0;
        for(i=1; i<=m; i++) {
            ans+=(n/i);
            ans+=i*(n/i-n/(i+1));
          }
        i--;
        if(n/i==m)
            ans-=m;

Topic links: https://vjudge.net/contest/304097#problem/H

Whether future flowers, from our present efforts

Guess you like

Origin blog.csdn.net/lylzsx20172018/article/details/90736370