Fibonacci
Time Limit: 1000MS |
Memory Limit: 65536K |
Total Submissions: 9524 |
Accepted: 6771 |
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 Fibonaccisequence is
.
Given an integer n, your goalis to compute the last 4 digits of Fn.
Input
The input test file will contain multipletest 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 thenumber −1.
Output
For each test case, print the last fourdigits of Fn. If the last four digits of Fn areall zeros, print ‘0’; otherwise, omit any leading zeros (i.e., print Fn mod10000).
Sample Input
0
9
999999999
1000000000
-1
Sample Output
0
34
626
6875
Hint
As a reminder, matrix multiplication isassociative, and the product of two 2 × 2 matrices is given by
.
Also, note that raising any 2 × 2 matrixto the 0th power gives the identity matrix:
.
本题的解法在题中已经讲得很清楚了。此题如果采用矩阵乘方的朴素算法,n过大时,会超时,所以在此采用矩阵乘方的快速幂算法。
有关快速幂的讲解如下:
矩阵的快速幂是用来高效地计算矩阵的高次方的。将朴素的o(n)的时间复杂度,降到log(n)。
这里先对原理(主要运用了矩阵乘法的结合律)做下简单形象的介绍:
一般一个矩阵的n次方,我们会通过连乘n-1次来得到它的n次幂。
但做下简单的改进就能减少连乘的次数,方法如下:
把n个矩阵进行两两分组,比如:A*A*A*A*A*A => (A*A)*(A*A)*(A*A)
这样变的好处是,你只需要计算一次A*A,然后将结果(A*A)连乘自己两次就能得到A^6,即(A*A)^3=A^6。算一下发现这次一共乘了3次,少于原来的5次。
其实大家还可以取A^3作为一个基本单位。原理都一样:利用矩阵乘法的结合律,来减少重复计算的次数。
以上都是取一个具体的数来作为最小单位的长度,这样做虽然能够改进效率,但缺陷也是很明显的,取个极限的例子,当n无穷大的时候,你现在所取的长度其实和1没什么区别。所以就需要我们找到一种与n增长速度”相适应“的”单位长度“,那这个长度到底怎么去取呢?这点是我们要思考的问题。
有了以上的知识,我们现在再来看看,到底怎么迅速地求得矩阵的N次幂。
既然要减少重复计算,那么就要充分利用现有的计算结果咯!怎么充分利用计算结果呢?这里考虑二分的思想。。
大家首先要认识到这一点:任何一个整数N,都能用二进制来表示。计算机处理的是离散的信息,都是以0,1来作为信号的处理的。可想而知二进制在计算机上起着举足轻重的地位。它能将模拟信号转化成数字信号,将原来连续的实际模型,用一个离散的算法模型来解决。
回头看看矩阵的快速幂问题,我们是不是也能把它离散化呢?比如A^19 => (A^16)*(A^2)*(A^1),显然采取这样的方式计算时因子数将是log(n)级别的(原来的因子数是n),不仅这样,因子间也是存在某种联系的,比如A^4能通过(A^2)*(A^2)得到,A^8又能通过(A^4)*(A^4)得到,这点也充分利用了现有的结果作为有利条件。下面举个例子进行说明:
现在要求A^156,而156(10)=10011100(2)
也就有A^156=>(A^4)*(A^8)*(A^16)*(A^128) 考虑到因子间的联系,我们从二进制10011100中的最右端开始计算到最左端。细节就说到这,下面给核心代码:
1 while(N)
2 {
3 if(N&1)
4 res=res*A;
5 n>>=1;
6 A=A*A;
7 }
里面的乘号,是矩阵乘的运算,res是结果矩阵。
本题的源代码如下:
C:
#include<stdio.h>
void matrix_mul(int a[2][2],int b[2][2],intmul[2][2])
{
inti,j,k;
intc[2][2];
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
c[i][j]=0;
for(k=0;k<2;k++)
{
c[i][j]=(c[i][j]+a[i][k]*b[k][j])%10000;
}
}
}
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
mul[i][j]=c[i][j];
}
}
}
int main()
{
intn;
while(scanf("%d",&n)!=EOF&&(n!=-1))
{
inta[2][2]={1,1,1,0};
intmul[2][2]={1,0,0,1};
while(n)
{
if(n&1)
{
matrix_mul(mul,a,mul); //注意理解参数的传递
}
n>>=1;
matrix_mul(a,a,a); //注意理解参数的传递
}
printf("%d\n",mul[0][1]);
}
return0;
}