[BZOJ2875][Noi2012]随机数生成器[等比数列求和+取模]
其实主要代码就是这个。。。
ull Sum(ull n,ull t) {//n是长度 t是首项 m是公比
if (n == 1) return t;
ull ret = Sum(n/2, t);
ret = (ret + mul(ret, Pow(m, n/2))) % mod;
if (n & 1) ret = (ret + mul(Pow(m, (n-1)), t))%mod;
return ret;
}
\(x[1] = (ax[0] + c) \pmod m\)
\(x[2] = a((ax[0] + c)+c) = a^2x[0] + ac + c \pmod m\)
\(x[3] = a(a^2x[0] + ac + c)+c = a^3x[0] + a^2c + ac + c \pmod m\)
\(x[i]\)的第一项是\(a^ix[0]\) 后面是一个首项为\(c\) 公比为\(a\)的等比数列
#include <bits/stdc++.h>
typedef unsigned long long ull;
using namespace std;
ull mod, a, c, x, n, g, mod1, m;
ull ret, ans;
inline ull mul(ull x,ull y) {//龟速乘法
for(ret = 0; y; y >>= 1) {
if (y & 1) ret = (ret + x) % mod;
x = (x + x) % mod;
}
return ret;
}
ull Pow(ull a,ull k) {//快速幂
ull x = a;
for(ans = 1; k; k >>= 1) {
if (k & 1) ans = mul(ans, x);
x = mul(x, x);
}
return ans;
}
ull Sum(ull n,ull t) {//n是长度 t是首项 m是公比
if (n == 1) return t;
ull ret = Sum(n/2, t);
ret = (ret + mul(ret, Pow(m, n/2))) % mod;
if (n & 1) ret = (ret + mul(Pow(m, (n-1)), t))%mod;
return ret;
}
int main() {
cin >> mod >> m >> c >> x >> n >> mod1;
ull ans = Pow(m, n);
ans = mul(ans, x);
ans = (ans + Sum(n, c)) % mod;
cout << ans % mod1;
return 0;
}