POJ - 3070 Fibonacci 解题报告

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;
}

注意每次求矩阵乘法要取模,不然数据太大了之后得到的就不是想要的结果了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值