您的位置:首页 > 其它

POJ - 3070 Fibonacci 解题报告

2017-05-09 23:56 393 查看
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 Fnare 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


题意是一道很经典的题求斐波那契数列中的某个数,很显然不能递归求解。根据题意就直接用矩阵快速幂。

{  1    1  }                         {  f2    f1  }

{  1    0  }       分别对应     {  f1    f0  }   ,而根据矩阵乘法行与列相乘,最后就会得到新矩阵对应位置的元素分别就是:

{  f2 + f1     f1 + f0(f2) }

{  f1 + f0(f2)    f1          }    ,这个就是矩阵相乘一次得到的东西,再自乘一次编号依次递增,所以就可以得到想要的结果了,附上代码:

#include <cstdio>
#include <string.h>
#include <string>
using namespace std;

class Solution {
public:
void Mult(int A[2][2], int B[2][2], int C[2][2])//矩阵乘法
{
int T[2][2];
memset(T, 0, sizeof(T));
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
for (int k = 0; k < 2; k++)
{
T[i][j] = (T[i][j] + A[i][k] * B[k][j]) % 10000;
}
}
}
memcpy(C, T, sizeof(T));

}

void Prep(int Ori[2][2], int Med[2][2], int k)//矩阵快速幂
{
if (k == 1)
{
memset(Med, 0, sizeof(int) * 4);
Med[0][0] = Med[0][1] = Med[1][0] = 1;
}
else if (k % 2 == 0)
{
Prep(Ori, Med, k / 2);
Mult(Med, Med, Med);
}
else
{
Prep(Ori, Med, k - 1);
Mult(Ori, Med, Med);
}
}

int GetAnwser()
{
int n;
scanf("%d", &n);
if (n == -1)
{
return -1;
}
if (n == 0)
{
return 0;
}
int Ori[2][2], Med[2][2];
memset(Ori, 0, sizeof(Ori));
Ori[0][0] = Ori[1][0] = Ori[0][1] = 1;
Prep(Ori, Med, n);
return Med[1][0];
}
};

int main()
{
int ans;
Solution Get;
while (1)
{
ans = Get.GetAnwser();
if (ans == -1)
{
break;
}
printf("%d\n", ans);
}
return 0;
}

注意每次求矩阵乘法要取模,不然数据太大了之后得到的就不是想要的结果了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: