---
id: 748
lang: en
translation_of: index.md
source_sha256: 50b45dafe5f9ea60d6e8b5988922d28b27240c4dcc0278cda9482645a45fa06f
title: "BZOJ1257: [CQOI2007] Sum of Remainders — Solution"
description: "Rewrite the sum as nk minus the sum of floor(k/i)*i; floor(k/i) stays equal over runs of consecutive i, so sum each run as an arithmetic series."
tags: ["OI","Math","Godlike","Number Theory","Segmentation","Modulo"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes: []
---

## A <span class="slang" data-zh="神仙" data-gloss="shénxiān, “immortal”. Someone, or a problem or idea, so brilliant it seems superhuman.">Godlike</span> Approach and Proof

The expression in this problem can be simplified to:

$$
nk-\sum_{i=1}^{n} \lfloor \frac{k}{i} \rfloor * i
$$

The first part is just a product. For the second part, intuition tells us that $\lfloor \frac{k}{i} \rfloor$ stays equal over a run of consecutive $i$, that is, it is piecewise. The sum of each piece can be computed directly as an arithmetic series. Let's look into the left and right endpoints of each piece. Suppose the target interval is $[i,?]$; then the value over this interval must be $\lfloor \frac{k}{i} \rfloor$, and solving backwards, the right endpoint is $\lfloor \frac{k}{\lfloor \frac{k}{i} \rfloor} \rfloor$. It can be proved that the right endpoint is greater than or equal to the left endpoint. Then just sum the arithmetic series.

## Code

```cpp
// BZ1257.cpp
#include <bits/stdc++.h>
#define ll long long
using namespace std;
ll n, k;
int main()
{
    scanf("%lld%lld", &n, &k);
    ll ans = n * k, gx;
    for (int x = 1; x <= n; x = gx + 1)
    {
        gx = (k / x) ? min(k / (k / x), n) : n;
        // x ~ gx same;
        ans -= (k / x) * (gx - x + 1) * (gx + x) / 2;
    }
    printf("%lld", ans);
    return 0;
}
```
