summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--content/math/divSum.cpp9
-rw-r--r--test/math/divSum.cpp48
2 files changed, 57 insertions, 0 deletions
diff --git a/content/math/divSum.cpp b/content/math/divSum.cpp
new file mode 100644
index 0000000..dc4bc4d
--- /dev/null
+++ b/content/math/divSum.cpp
@@ -0,0 +1,9 @@
+// Calculates the sum of (a*i+b)/m for i=0..(n-1) in O(log(n))
+// Note that b should not be negative!
+ll divSum(ll n, ll m, ll a, ll b){
+ if(m == 0) return 0;
+ ll ans = a/m * n*(n-1) / 2 + b/m * n;
+ a %= m, b %= m;
+ ll y = (a*(n-1)+b)/m;
+ return ans + y*(n-1) - divSum(y, a, m, m-b-1);
+} \ No newline at end of file
diff --git a/test/math/divSum.cpp b/test/math/divSum.cpp
new file mode 100644
index 0000000..1f82387
--- /dev/null
+++ b/test/math/divSum.cpp
@@ -0,0 +1,48 @@
+#include "../util.h"
+#include <math/divSum.cpp>
+
+ll naive(ll n, ll m, ll a, ll b){
+ ll ans = 0;
+ for(ll i = 0; i < n; i++){
+ ans += (a*i+b)/m;
+ }
+ return ans;
+}
+
+void stress_test() {
+ ll queries = 0;
+ for (ll i = 0; i < 10'000; i++) {
+ int n = Random::integer<int>(1, 100);
+ int m = Random::integer<int>(1, 100);
+ int a = Random::integer<int>(0, 100);
+ int b = Random::integer<int>(0, 100);
+ ll expected = naive(n, m, a, b);
+ ll got = divSum(n, m, a, b);
+ if (got != expected) cerr << "got: " << got << ", expected: " << expected << FAIL;
+ queries++;
+ }
+ cerr << "tested queries: " << queries << endl;
+}
+
+constexpr int N = 1'000'000;
+void performance_test() {
+ timer t;
+ hash_t hash = 0;
+ for (int operations = 0; operations < N; operations++) {
+ ll n = Random::integer<ll>(1, 1'000'000'000);
+ ll m = Random::integer<ll>(1, 1'000'000'000);
+ ll a = Random::integer<ll>(0, 1'000'000'000);
+ ll b = Random::integer<ll>(0, 1'000'000'000);
+ t.start();
+ hash += divSum(n, m, a, b);
+ t.stop();
+ }
+ if (t.time > 750) cerr << "too slow: " << t.time << FAIL;
+ cerr << "tested performance: " << t.time << "ms (hash: " << hash << ")" << endl;
+}
+
+int main() {
+ stress_test();
+ performance_test();
+}
+