一类求和问题——类欧几里得
转载自:https://zhuanlan.zhihu.com/p/34650451
今天要来介绍的是用类欧几里得算法来解决一类求和问题。
模板题
给出 $n, a, b, c$,对于每组数据,分别输出 $f, h, g$ 的值,答案对 $998244353$ 取模。($n \leq 10^9$)
//由于这三个函数是互相依赖的,所以我们将其放在一个函数里求解
//分别算会产生大量的重复计算
#include <cstdio> #include <iostream> using namespace std; const long long inv2 = 499122177; const long long inv6 = 166374059; const long long mod = 998244353; int t; long long n, a, b, c; struct query { long long f; long long g; long long h; }; long long read() { long long ans = 0; char ch; while(!isdigit(ch = getchar())); while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + (ch ^ 48), ch = getchar(); return ans; } query solve(long long a, long long b, long long c, long long n) { query ans, prec; if(a == 0) { ans.f = (b / c) * (n + 1) % mod; ans.g = (b / c) * n % mod * (n + 1) % mod * inv2 % mod; ans.h = (b / c) * (b / c) % mod * (n + 1) % mod; } else if(a >= c || b >= c) { prec = solve(a % c, b % c, c, n); ans.f = (prec.f + n * (n + 1) % mod * inv2 % mod * (a / c) % mod + (n + 1) * (b / c) % mod) % mod; ans.g = ((a / c) * n % mod * (n + 1) % mod * (2 * n + 1) % mod * inv6 % mod + (b / c) * n % mod * (n + 1) % mod * inv2 % mod + prec.g) % mod; ans.h = (prec.h + (a / c) * (a / c) % mod * n % mod * (n + 1) % mod * (2 * n + 1) % mod * inv6 % mod + (n + 1) * (b / c) % mod * (b / c) % mod + 2 * (a / c) % mod * prec.g % mod + 2 * (b / c) % mod * prec.f % mod + 2 * (a / c) % mod * (b / c) % mod * n % mod * (n + 1) % mod * inv2 % mod) % mod; } else { long long m = (a * n + b) / c; prec = solve(c, c - b - 1, a, m - 1); ans.f = (n * (m % mod) % mod - prec.f) % mod; ans.g = (n * (n + 1) % mod * (m % mod) % mod - prec.f - prec.h) % mod * inv2 % mod; ans.h = (n * (m % mod) % mod * ((m + 1) % mod) % mod - 2 * prec.g - 2 * prec.f - ans.f) % mod; } return ans; } int main() { scanf("%d", &t); while(t--) { scanf("%lld %lld %lld %lld", &n, &a, &b, &c); query ans = solve(a, b, c, n); printf("%lld %lld %lld\n", (ans.f + mod) % mod, (ans.h + mod) % mod, (ans.g + mod) % mod); } return 0; }
求f
$\displaystyle f(a, b, c, n) = \sum_{i=0}^n\left \lfloor \frac{ai+b}{c} \right \rfloor$
#include<bits/stdc++.h> using namespace std; typedef long long ll; const ll mod = 1e9+7; ll f(ll a, ll b, ll c, ll n) { if(!a) return (b/c)*(n+1)%mod; if(a >= c || b >= c) return (f(a%c, b%c, c, n) + n*(n+1)/2%mod*(a/c)%mod + (n+1)*(b/c)%mod) % mod; ll m = (a*n+b) / c; return (n*m%mod - f(c, c-b-1, a, m-1) + mod)%mod; } int main() { printf("%lld\n", f(1, 0, 2, 5)); //0+1+1+2+2=6 }
个性签名:时间会解决一切