G - Harmonic Number (II)

General idea: Question meaning: Given an n, let you find Σn/i, i from 1->n.

 

PS: This rule is really hard to find according to conventional thinking

The rule is as follows: 
for a value n / i, there are n / i - n / ( i +1 ), 
but this is O(n), and 2^32 is violent. Elsewhere. So it is found that when this number (n / i) is greater than sqrt(n), n / i can be calculated violently, and the number that is less than the number is calculated by the law and then multiplied by this number.

 

 

 

 

#include <iostream>
#include <cstdio>
#include <cmath>


using namespace std;

int t;
long long n,ans;

intmain ()
{
    ios::sync_with_stdio(false);
    cin>>t;
    for(int j=1;j<=t;j++)
    {
        ans=0;
        long long i;
        cin>>n;
        for(i=1;i<=sqrt(n);i++)
        {
            ans+=n/i;
            if(n/i>n/(i+1)) ans+=(n/i-n/(i+1))*i;

        }
    if (n / (i - 1 ) == i - 1 ) // When judging coincidence, we need to subtract repeated 
        ans -= n / (i - 1 );
    printf ("Case %lld: %lld\n", j, ans);
    }

    return 0;
}

          

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324769457&siteId=291194637