From 6e2b2587a10da903d588318faa28f9af66ba8c50 Mon Sep 17 00:00:00 2001 From: rsk0315 Date: Wed, 16 Dec 2020 14:41:15 +0900 Subject: [PATCH 1/3] Improve floor_sum --- atcoder/math.hpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/atcoder/math.hpp b/atcoder/math.hpp index ec5bca5..13fbf6b 100644 --- a/atcoder/math.hpp +++ b/atcoder/math.hpp @@ -90,10 +90,11 @@ long long floor_sum(long long n, long long m, long long a, long long b) { b %= m; } - long long y_max = (a * n + b) / m, x_max = (y_max * m - b); - if (y_max == 0) return ans; - ans += (n - (x_max + a - 1) / a) * y_max; - ans += floor_sum(y_max, a, m, (a - x_max % a) % a); + long long y_max = a * (n - 1) + b; + if (y_max < m) return ans; + long long y_max_div = y_max / m; + long long y_max_mod = y_max % m; + ans += y_max_div + floor_sum(y_max_div, a, m, y_max_mod); return ans; } From 42011962c40ad184210c57511b58faede18bff14 Mon Sep 17 00:00:00 2001 From: rsk0315 Date: Wed, 16 Dec 2020 15:46:48 +0900 Subject: [PATCH 2/3] Change the order of operation in case of the overflow --- atcoder/math.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/atcoder/math.hpp b/atcoder/math.hpp index 13fbf6b..f8723a4 100644 --- a/atcoder/math.hpp +++ b/atcoder/math.hpp @@ -82,7 +82,7 @@ std::pair crt(const std::vector& r, long long floor_sum(long long n, long long m, long long a, long long b) { long long ans = 0; if (a >= m) { - ans += (n - 1) * n * (a / m) / 2; + ans += (n - 1) * n / 2 * (a / m); a %= m; } if (b >= m) { From a596e83d4ca193eb220dee00ccc908373a6a3117 Mon Sep 17 00:00:00 2001 From: rsk0315 Date: Wed, 16 Dec 2020 15:49:16 +0900 Subject: [PATCH 3/3] Reduce operations per function call --- atcoder/math.hpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/atcoder/math.hpp b/atcoder/math.hpp index f8723a4..0b6e366 100644 --- a/atcoder/math.hpp +++ b/atcoder/math.hpp @@ -90,11 +90,9 @@ long long floor_sum(long long n, long long m, long long a, long long b) { b %= m; } - long long y_max = a * (n - 1) + b; + long long y_max = a * n + b; if (y_max < m) return ans; - long long y_max_div = y_max / m; - long long y_max_mod = y_max % m; - ans += y_max_div + floor_sum(y_max_div, a, m, y_max_mod); + ans += floor_sum(y_max / m, a, m, y_max % m); return ans; }