博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
POJ 3070 Fibonacci【斐波那契数列/矩阵快速幂】
阅读量:4353 次
发布时间:2019-06-07

本文共 1914 字,大约阅读时间需要 6 分钟。

Fibonacci
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 17171   Accepted: 11999

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

099999999991000000000-1

Sample Output

0346266875

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

【分析】:矩乘其实很简单,通过自己构造或者是搜索对于一个递推公式求出它所对应的常数矩阵,然后套个快速幂就可以迅速求解第n项。
最后输出的是矩阵最左上方的值。
根据前面的一些思路,现在我们需要构造一个2 x 2的矩阵,使得它乘以(a,b)得到的结果是(b,a+b)。每多乘一次这个矩阵,这两个数就会多迭代一次。那么,我们把这个2 x 2的矩阵自乘n次,再乘以(0,1)就可以得到第n个Fibonacci数了。不用多想,这个2 x 2的矩阵很容易构造出来。
【代码】:
#include 
#include
#include
#include
using namespace std;typedef long long ll;const int mod=10000;typedef vector
vec;typedef vector
mat;mat mul(mat &a,mat &b){ mat c(a.size(),vec(b[0].size())); for(int i=0;i<2;i++) for(int j=0;j<2;j++) for(int k=0;k<2;k++){ c[i][j]+=a[i][k]*b[k][j]; c[i][j]%=mod; } return c;}mat Pow(mat a,ll n){ mat res(a.size(),vec(a.size())); for(int i=0;i
>n&&n!=-1) { cout<
<
斐波那契快速幂

 

转载于:https://www.cnblogs.com/Roni-i/p/8350614.html

你可能感兴趣的文章
C#各种加密解密算法
查看>>
起泡排序(Bubble sort)
查看>>
Linux下c语言实现myod
查看>>
关于网站内文档url的加密(待写)
查看>>
09 ssh
查看>>
ionic day01教程第一天之多平台运行(ios & android)
查看>>
第四届蓝桥杯c/c++B组7
查看>>
自定义控件 闪烁效果的TextView
查看>>
linux磁盘分区fdisk命令详解
查看>>
虚拟机vmware centos7 扩展磁盘空间
查看>>
关于github在客户端不小心删除新仓库,重建后无法上传解决方法
查看>>
SQLServer存储过程中事务的使用
查看>>
Hive SQL 分类
查看>>
头文件中尽量少引用命名空间
查看>>
stopPropagation, preventDefault 和 return false 的区别
查看>>
Python和open course
查看>>
python爬虫-基础入门-爬取整个网站《1》
查看>>
保持一个乐观的心态
查看>>
最佳实践(二)
查看>>
【Windows】线程漫谈——线程同步之信号量和互斥量
查看>>