Skip to content

Commit 7c3b484

Browse files
committed
Improve floor_sum
atcoder/ac-library#88
1 parent 3761917 commit 7c3b484

File tree

1 file changed

+4
-6
lines changed

1 file changed

+4
-6
lines changed

src/math.rs

+4-6
Original file line numberDiff line numberDiff line change
@@ -188,21 +188,19 @@ pub fn crt(r: &[i64], m: &[i64]) -> (i64, i64) {
188188
pub fn floor_sum(n: i64, m: i64, mut a: i64, mut b: i64) -> i64 {
189189
let mut ans = 0;
190190
if a >= m {
191-
ans += (n - 1) * n * (a / m) / 2;
191+
ans += (n - 1) * n / 2 * (a / m);
192192
a %= m;
193193
}
194194
if b >= m {
195195
ans += n * (b / m);
196196
b %= m;
197197
}
198198

199-
let y_max = (a * n + b) / m;
200-
let x_max = y_max * m - b;
201-
if y_max == 0 {
199+
let y_max = a * n + b;
200+
if y_max < m {
202201
return ans;
203202
}
204-
ans += (n - (x_max + a - 1) / a) * y_max;
205-
ans += floor_sum(y_max, a, m, (a - x_max % a) % a);
203+
ans += floor_sum(y_max / m, a, m, y_max % m);
206204
ans
207205
}
208206

0 commit comments

Comments
 (0)