Ultraviolet A 10689-yet another number sequence
Question Link
Question: Fibonacci gives the first two items, obtains the nth item, and retains the M bit.
Idea: the bare matrix is a fast power, that is, the modulo value is 10 ^ m.
Code:
#include <cstdio>#include <cstring>const int mod[5] = {0, 10, 100, 1000, 10000};int t, a, b, n, m;struct mat {int v[2][2];mat() {memset(v, 0, sizeof(v));}mat operator * (mat c) {mat ans;for (int i = 0; i < 2; i++) {for (int j = 0; j < 2; j++) {for (int k = 0; k < 2; k++) {ans.v[i][j] = (ans.v[i][j] + v[i][k] * c.v[k][j]) % mod[m];}}}return ans;}};mat pow_mod(mat x, int k) {mat ans;ans.v[0][0] = ans.v[1][1] = 1;while (k) {if (k&1) ans = ans * x;x = x * x;k >>= 1;}return ans;}int solve() {if (n == 0) return a;if (n == 1) return b;mat ans;ans.v[0][0] = ans.v[0][1] = ans.v[1][0] = 1;ans = pow_mod(ans, n - 1);return (ans.v[0][0] * b + ans.v[0][1] * a);}int main() {scanf("%d", &t);while (t--) {scanf("%d%d%d%d", &a, &b, &n, &m);printf("%d\n", solve() % mod[m]);}return 0;}