Ultraviolet A 10689-yet another number sequence (matrix fast power)

Source: Internet
Author: User
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;}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.