Fibonacci POJ

来源:互联网 发布:社交网络信息 综述 编辑:程序博客网 时间:2024/09/21 13:36

In the Fibonacci integer sequence, F0 = 0,F1 = 1, andFn =Fn − 1 +Fn − 2 forn ≥ 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 ofFn are all zeros, print ‘0’; otherwise, omit any leading zeros (i.e., printFn 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:

.


做这个题真的是开眼了,以前不知道有矩阵快速幂QAQ,看来矩阵快速幂是可以优化递推关系的

操作过程如同对数的快速幂,我自己推了一遍矩阵表达式,推出来的不是给出的那个,而是如下这个

(图是抄的)

这样的话就要>=1,当n是0的时候直接输出0就可以了。还有,用结构体里存放矩阵的话非常清晰方便,比不用来的要清晰简单得多。

#include<stdio.h>#include<string.h>using namespace std;struct aa{    int m[3][3];};aa mx(aa a,aa b){    aa res;    memset(res.m,0,sizeof(res.m));    for(int i=1; i<=2; i++)        for(int j=1; j<=2; j++)            for(int k=1; k<=2; k++)            {                res.m[i][j]+=(a.m[i][k]*b.m[k][j]);                res.ma[i][j]%=10000;            }    return res;}int fast_mod(aa x,long long y){    aa ans;    ans.m[1][1]=ans.m[2][2]=1;    ans.m[1][2]=ans.m[2][1]=0;    while(y)    {        if(y&1)        {            ans=mx(ans,x);        }        y=y>>1;        x=mx(x,x);    }    return ans.m[1][1];}int main(){    long long n;    while(scanf("%lld",&n)!=EOF)    {        if(n<0)            break;        aa x;        x.m[1][1]=x.m[1][2]=x.m[2][1]=1;        x.m[2][2]=0;        if(n==0)            printf("0\n");        else        printf("%d\n",fast_mod(x,n-1));    }}


原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 近邻宝箱子打开了东西忘记拿怎么办 京东取消订单商家总不取消怎么办 京东快递退货取件一直取不到怎么办 在京东线上付款了但没收到货怎么办 寄快递收件人电话号码写错了怎么办 京东购物实名认证被别人占用怎么办 货已发出单号还没填买家退货怎么办 自提柜还有一个包忘记拿怎么办 当顾客说衣服太贵的时候怎么办 京东快递送错了被别人签收了怎么办 乐视1s玩王者荣耀卡怎么办 京东商城买东西发现地址错了怎么办 京东分期付款买手机额度不够怎么办 亮皮银色高跟鞋时间放久变色怎么办 饿了么商家钱包提现被锁了怎么办 在淘手游买的游戏账号被找回怎么办 交易猫买手游梦幻号被找回了怎么办 绑定着苹果账号的邮箱忘记了怎么办 京东注册账号跟密码都忘记了怎么办 孩子大学一个宿舍宿友不行怎么办 微信手机支付密码忘记了怎么办 微信公众号不能付款了怎么办 头条误点了投放头条广告怎么办 交行网银密码错误6次怎么办 宁波新冮厦关门我们的消费卡怎么办 第一天上班别人教的学不会怎么办 老公出轨已经不想跟你爱爱了怎么办 妻子出轨丈夫为了孩子不离婚怎么办 妻子出轨分居死也不愿意离婚怎么办 拼多多个人卖家登录密码忘了怎么办 微信被限制添加更多订阅号了怎么办 知网复制粘贴的论文有格式怎么办 知网论文查询网站密码忘记了怎么办 开通了超级会员不能克隆好友怎么办 偷了家里好多钱去买手机了怎么办 中行信用卡短信邀请办白金卡怎么办 注册邮箱说邮箱地址已被注册怎么办 便利店开在小区里面没生意怎么办 微信支付密码忘了怎么办没银行卡 中行5月扣很多钱是怎么办 中银淘宝校园卡影响征信问题怎么办