Fibonacci
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 8308 Accepted: 5910
Description
In the Fibonacci integer sequence, F0 = 0, F1 = 1, and Fn = Fn − 1 + Fn − 2 for n ≥ 2. For example, the first ten terms of the Fibonacci sequence are:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …
An alternative formula for the Fibonacci sequence is
.
Given an integer n, your goal is to compute the last 4 digits of Fn.
Input
The input test file will contain multiple test cases. Each test case consists of a single line containing n (where 0 ≤ n ≤ 1,000,000,000). The end-of-file is denoted by a single line containing the number −1.
Output
For each test case, print the last four digits of Fn. If the last four digits of Fn are all zeros, print ‘0’; otherwise, omit any leading zeros (i.e., print Fn mod 10000).
Sample Input
0
9
999999999
1000000000
-1
Sample Output
0
34
626
6875
Hint
As a reminder, matrix multiplication is associative, and the product of two 2 × 2 matrices is given by
.
Also, note that raising any 2 × 2 matrix to the 0th power gives the identity matrix:
.
代码:
解析:
如果a* b % c == ((a % c)*(b % c)) % c;
矩阵快速幂。利用,可化为矩阵快速幂,即:由于矩阵乘法具有结合律,因此对于矩阵A,有A^4 = A * A * A * A = (A*A) * (A*A) = A^2 * A^2。我们可以得到这样的结论:当n为偶数时,A^n = A^(n/2) * A^(n/2);当n为奇数时,A^n = A^(n/2) * A^(n/2) * A (其中n/2取整)。
#include<stdio.h>
#include<string.h>
#define mac 10000;
typedef struct
{
int v[2][2];
}M;
M m;
M mul(M a, M b)
{
M c;
c.v[0][0] = (a.v[0][0] * b.v[0][0] + a.v[0][1] * b.v[1][0]) % mac;
c.v[0][1] = (a.v[0][0] * b.v[0][1] + a.v[0][1] * b.v[1][1]) % mac;
c.v[1][0] = (a.v[1][0] * b.v[0][0] + a.v[1][1] * b.v[1][0]) % mac;
c.v[1][1] = (a.v[1][0] * b.v[0][1] + a.v[1][1] * b.v[1][1]) % mac;
return c;
}
M quick(M f, int k)//不断的往下递归,直到k = 1, 返回以后求矩阵的2次方;
{
if(k == 1)
{
return f;
}
f = quick(f,k / 2);
if(k % 2 == 0)
{
f = mul(f, f);
}
else
{
f = mul(mul(f, f), m);
}
return f;
}
int main()
{
int n;
M f;
m.v[0][0] = 1; m.v[0][1] = 1;
m.v[1][0] = 1; m.v[1][1] = 0;
while(scanf("%d", &n), n != -1)
{
memset(f.v, 0, sizeof(f.v));
if(n == 0)
{
printf("0\n");
continue;
}
f = quick(m, n);
printf("%d\n", f.v[0][1] % mac);
}
return 0;
}