Codeforces 616E Sum of Remainders 【数学分块】

题目链接:Codeforces 616E Sum of Remainders

E. Sum of Remainders
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
Calculate the value of the sum: n mod 1 + n mod 2 + n mod 3 + … + n mod m. As the result can be very large, you should print the value modulo 109 + 7 (the remainder when divided by 109 + 7).

The modulo operator a mod b stands for the remainder after dividing a by b. For example 10 mod 3 = 1.

Input
The only line contains two integers n, m (1 ≤ n, m ≤ 1013) — the parameters of the sum.

Output
Print integer s — the value of the required sum modulo 109 + 7.

Examples
input
3 4
output
4
input
4 4
output
1
input
1 1
output
0

题意:求解 mi=1nmodi

思路:我们化简 nmodi=nn/ii
这样原式 =nmmi=1(n/ii)
首先 m<=n 时,直接暴力,对于剩下的,我们可以分块来搞,总会存在一段连续的值使得 n/i 为定值,那么我们找到这个区间就可以了。不过貌似在除以2的时候,会出问题,我直接上逆元就过了。

AC代码:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#define INF 0x7fffffff
using namespace std;
typedef long long LL;
const int MAXN = 1e6 + 10;
const int MOD = 1e9 + 7;
void add(LL &x, LL y) {x += y; x %= MOD;}
LL pow_mod(LL a, LL n) {
    LL ans = 1LL;
    while(n) {
        if(n & 1)
            ans = ans * a % MOD;
        a = a * a % MOD;
        n >>= 1;
    }
    return ans;
}
int main()
{
    LL n, m; scanf("%lld%lld", &n, &m);
//    LL s = 0;
//    for(LL i = 1; i <= m; i++) {
//        add(s, n % i % MOD);
//    }
//    cout << s << endl;
    LL ans = n % MOD * (m % MOD) % MOD;
    LL nn = sqrt(n);
    LL ans1 = 0;
    for(LL i = 1; i <= min(m, nn); i++) {
        add(ans1, n / i % MOD * i % MOD);
    }
    //cout << ans1 << endl;
    if(m > nn) {
        if(nn * nn == n) nn--;
        for(LL i = 1; i <= nn; i++) {
            LL r = min(m, n / i); LL l = n / (i + 1) + 1;
            if(l > r || r <= nn) continue;
            //cout << l << ' ' << r << endl;
            add(ans1, (l + r) % MOD * ((r - l + 1) % MOD) % MOD * pow_mod(2, MOD-2) % MOD * i % MOD);
        }
    }
    printf("%lld\n", ((ans - ans1) % MOD + MOD) % MOD);
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值