Fibonacci
题目联接:http://acm.tzc.edu.cn/acmhome/problemdetail.do?&method=showdetail&contestId=282&id=3492
Fibonacci
Total Submit: 15 Accepted: 11
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
分析:
用编程之美上提到的分治策略,即有些人讲的快速指数相乘法。
代码:
View Code #include<iostream>
using namespace std;
void multiply(int *a, int *b) //计算矩阵乘法(模4)
{
int tmp1[4], tmp2[4];
int i;
for (i=0; i<4; i++) tmp1[i]=a[i];
for (i=0; i<4; i++) tmp2[i]=b[i];
a[0]=(tmp1[0]*tmp2[0] + tmp1[1]*tmp2[2])%10000;
a[1]=(tmp1[0]*tmp2[1] + tmp1[1]*tmp2[3])%10000;
a[2]=(tmp1[2]*tmp2[0] + tmp1[3]*tmp2[2])%10000;
a[3]=(tmp1[2]*tmp2[1] + tmp1[3]*tmp2[3])%10000;
}
int main()
{
long n;
while (cin>>n, n!=-1)
{
int a[4]={1, 0, 0, 1}; //存放矩阵A^n;
int tmp[4]={1, 1, 1, 0}; //存放矩阵A^i;
for (; n; n>>=1) //快速指数相乘法
{
if (n&1)
{
multiply(a,tmp);
}
multiply(tmp,tmp);
}
cout<<a[1]<<endl;
}
return 0;
}

浙公网安备 33010602011771号