码迷,mamicode.com
首页 > 其他好文 > 详细

UESTC - 278 Fibonacci(矩阵快速幂)

时间:2016-08-20 00:15:05      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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., printFn 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:

技术分享.


这个题目和CSU上面的一个题目差不多,点击打开我的博客

代码:

#include<iostream>
using namespace std;

int a, b, c, d;
int x1, x2, x3, x4;

void f(int n)
{
	if (n == 0)
	{
		a = 1;
		b = 0;
		c = 0;
		d = 1;
		return;
	}
	f(n / 2);
	x1 = a*a + b*c;
	x2 = (a + d)*b;
	x3 = (a + d)*c;
	x4 = b*c + d*d;
	a = x1 % 10000;
	b = x2 % 10000;
	c = x3 % 10000;
	d = x4 % 10000;
	if (n % 2)
	{
		c += a;
		a = c - a;
		d += b;
		b = d - b;
	}
}

int main()
{
	int n;
	while (cin >> n)
	{
		if (n < 0)break;
		f(n);
		cout << b << endl;
	}
	return 0;
}


2个题目都是斐波那契数列,所以函数 f 一模一样,没有改直接用了。

同样的,这个题目我也考虑了周期的问题。

因为这个题目是mod 10000,不是1000000007

一方面10000很小,另外一方面1000000007是素数,差别很大。

经过枚举,我找到了,斐波那契数列的第15000项是0,第15001项是1

刚好可以对应上第0项是0,第1项是1。

那么15000是不是最小周期呢?

(不得不说15000这个数真的很巧,1000000007那个周期是1000000007*2,

不知道是不是有某种数量关系)



UESTC - 278 Fibonacci(矩阵快速幂)

标签:

原文地址:http://blog.csdn.net/nameofcsdn/article/details/52254528

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!