首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >【POJ】3070 - Fibonacci(矩阵快速幂)

【POJ】3070 - Fibonacci(矩阵快速幂)

作者头像
FishWang
发布2025-08-26 19:57:49
发布2025-08-26 19:57:49
11100
代码可运行
举报
运行总次数:0
代码可运行

点击打开题目

Fibonacci

Time Limit: 1000MS

Memory Limit: 65536K

Total Submissions: 12951

Accepted: 9210

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

代码语言:javascript
代码运行次数:0
运行
复制
0
9
999999999
1000000000
-1

Sample Output

代码语言:javascript
代码运行次数:0
运行
复制
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:

.

Source

Stanford Local 2006

这道题大概就是矩阵快速幂的基本模板了。注释说的清楚。

注意下矩阵相乘的下标就行了。

代码如下:

代码语言:javascript
代码运行次数:0
运行
复制
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define CLR(a,b) memset(a,b,sizeof(a))
#define MOD 10000
struct Matrix
{
	__int64 a[4][4];		//矩阵
	int h,w;		//行、列 
}pr,ans;
void init()		//初始化矩阵 
{
	ans.a[2][1] = ans.a[1][2] = 0;
	ans.h = ans.w = 2;
	for (int i = 1 ; i <= 2 ; i++)		//初始化单位矩阵 
		ans.a[i][i] = 1;
	pr.a[1][1] = pr.a[1][2] = pr.a[2][1] = 1;		//初始化初始矩阵 
	pr.a[2][2] = 0;
	pr.w = 2;
	pr.h = 2;
}
Matrix Matrix_multiply(Matrix x , Matrix y)		//矩阵乘法 
{
	Matrix t;
	CLR(t.a,0);
	t.h = x.h;		//新矩阵的行数为x的行数 
	t.w = y.w;		//新矩阵的列数为y的列数 
	for (int i = 1 ; i <= x.h ; i++)
	{
		for (int j = 1 ; j <= x.w ; j++)
		{
			if (x.a[i][j] == 0)
				continue;
			for (int k = 1 ; k <= y.w ; k++)
				t.a[i][k] = (t.a[i][k] + x.a[i][j] * y.a[j][k] % MOD) % MOD;
		}
	}
	return t;
}
void Matrix_mod(int n)		//矩阵快速幂
{
	while (n)
	{
		if (n & 1)
			ans = Matrix_multiply(pr , ans);
		pr = Matrix_multiply(pr , pr);
		n >>= 1;
	}
}
int main()
{
	int n;
	while (~scanf ("%d",&n) && n != -1)
	{
		init();
		Matrix_mod(n);
		printf ("%I64d\n",ans.a[1][2] % MOD);
	}
	return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-08-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档