ACM1005:Number Sequence
Problem Description
A number sequence is defined as follows:
f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.
Given A, B, and n, you are to calculate the value of f(n).
f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.
Given A, B, and n, you are to calculate the value of f(n).
Input
The input consists of multiple test cases. Each test case contains 3 integers A, B and n on a single line (1 <= A, B <= 1000, 1 <= n <= 100,000,000). Three zeros signal the end of input and this test case is not to be processed.
Output
For each test case, print the value of f(n) on a single line.
Sample Input
1 1 3
1 2 10
0 0 0
Sample Output
2
5
------------------------------------------------------------------------------------------------------------------
#include<stdio.h>
#include<string.h>
#define SIZE 2
long long int ** multiple(long long int a[][SIZE], long long int b[][SIZE]);
int main()
{
int A, B;
long long int n;
long long int factor[SIZE][SIZE];
long long int ans[SIZE][SIZE];
while (scanf("%d%d%lld", &A, &B, &n) && (A||B||n))
{
memset(factor, 0, 2 * 2 * sizeof(int));
memset(ans, 0, 2 * 2 * sizeof(int));
factor[0][0] = A;
factor[0][1] = B;
factor[1][0] = 1;
factor[1][1] = 0;
//矩阵快速幂
for (int i = 0; i < SIZE; i++)
ans[i][i] = 1;
n = n - 2;
while (n > 0)
{
if (n & 1)
memcpy(ans, multiple(ans, factor), 2 * 2 * sizeof(long long int));
memcpy(factor, multiple(factor, factor), 2 * 2 * sizeof(long long int));
n >>= 1;
}
printf("%lld\n", (ans[0][0] + ans[0][1]) % 7);
}
return 0;
}
long long int ** multiple(long long int a[][SIZE], long long int b[][SIZE])
{
int i, j, k;
long long int c[SIZE][SIZE];
memset(c, 0, 2 * 2 * sizeof(long long int));
for(i = 0; i < SIZE; i++)
for(j = 0; j < SIZE; j++)
for (k = 0; k < SIZE; k++)
{
c[i][j] += a[i][k] * b[k][j];
c[i][j] = c[i][j] % 7;
}
return c;
}
参考文章:
https://blog.csdn.net/codeswarrior/article/details/81258928
https://www.cnblogs.com/cmmdc/p/6936196.html

浙公网安备 33010602011771号