[CF616E] Sum of Remainders

Description

(sum_{i=1}^m ( n mod i))(n,m le 10^{13})

Solution

考虑使得 ([n/i]) 相同的一段 (i),设为 ([l,r]),则

[sum_{i=l}^r n mod i = n(r-l+1)-[frac n l] (frac {r(r+1)} 2 - frac {l(l+1)} 2) ]

可以在 (O(1)) 时间内计算,故时间复杂度 (O(sqrt n))

取模坑!

#include <bits/stdc++.h>
using namespace std;

#define int long long
#define LL int
const int N = 1000005;
const int mod = 1e9+7;

int n,m;

int get(int l,int r)
{
    int t=n/l;
    r%=mod;
    l%=mod;
    return (t)%mod* ((l+r)%mod*((r-l+1+mod)%mod)%mod*(mod/2+1)%mod) %mod;
}

signed main()
{
    ios::sync_with_stdio(false);
    int ans=0;
    cin>>n>>m;
    int l=1,r;
    ans=(n%mod)*(m%mod)%mod;
    while(l<=min(n,m))
    {
        r=n/(n/l);
        r=min(r,m);
        ans-=get(l,r);
        ans%=mod;
        ans+=mod;
        ans%=mod;
        l=r+1;
    }
    ans%=mod;
    cout<<ans<<endl;
}

原文地址:https://www.cnblogs.com/mollnn/p/13583143.html