Problem J
How Many Calls?
Input: standard input
Output: standard output
Time Limit: 5 seconds
The fibonacci number is defined by the following recurrence:
- fib(0) = 0
- fib(1) = 1
- fib(n) = fib(n-1)+fib(n-2)
But we're not interested in the fibonacci numbers here. We would like to know how many calls does it take to evaluate the n th fibonacci number if we follow the given recurrence. Since the numbers are going to be quite large, we'd like to make the job a bit easy for you. We'd only need the last digit of the number of calls, when this number is represented in base b.
Input
Input consists of several test cases. For each test you'd be given two integers n (0 <= n < 263-1), b (0 < b <= 10000). Input is terminated by a test case where n=0 and b=0, you must not process this test case.
Output
For each test case, print the test case number first. Then print n, b and the last digit (in base b) of the number of calls. There would be a single space in between the two numbers of a line. Note that the last digit has to be represented in decimal number system.
Sample Input
0 100
1 100
2 100
3 100
10 10
0 0
Sample Output
Case 1: 0 100 1
Case 2: 1 100 1
Case 3: 2 100 3
Case 4: 3 100 5
Case 5: 10 10 7
F(n) = F(n - 2) + F(n - 1) + 1 = 2 * fib(n) - 1;
思路:矩阵快速幂求斐波那契第n个数。
代码:
#include <stdio.h>
#include <string.h>
long long n;
int b;
struct mat {
int v[2][2];
mat() {
memset(v, 0, sizeof(v));
}
mat operator * (mat &a) {
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] * a.v[k][j]) % b;
}
return ans;
}
}a;
mat pow_mod(mat a, long long k) {
if (k == 1 || k == 0)
return a;
mat c = pow_mod(a * a, k / 2);
if (k & 1)
c = c * a;
return c;
}
int main() {
int t = 1;
while (~scanf("%lld%d", &n, &b) && n || b) {
a.v[0][0] = a.v[0][1] = a.v[1][0] = 1;
mat c = pow_mod(a, n);
printf("Case %d: %lld %d %d\n", t ++, n, b, (2 * c.v[0][0] - 1 + b) % b);
}
return 0;
}