uva 10229 Modular Fibonacci

原题:
The Fibonacci numbers (0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, …) are defined by the recurrence:
F 0 = 0
F 1 =1
F i = F i−1 + F i−2 for i > 1
Write a program which calculates M n = F n mod 2 m for given pair of n and m. 0 ≤ n ≤ 2147483647
and 0 ≤ m < 20. Note that a mod b gives the remainder when a is divided by b.
Input
Input consists of several lines specifying a pair of n and m.
Output
Output should be corresponding M n , one per line.
Sample Input
11 7
11 6
Sample Output
89
25

中文:
让你计算fn mod 2^m次幂的结果,其中fn为斐波那契数列。

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll pow2[21];
ll circle[21];
ll solve(ll n,ll m)
{
    n=n%circle[m];
    if(m==0||n==0)
    return 0;
    if(n==1)
    return 1;
    ll f1=0,f2=1,f3;
    for(int i=2;i<=n;i++)
    {
        f3=(f1+f2)%pow2[m];
        f1=f2;
        f2=f3;
    } 
    return f3;
}
int main()
{
    ios::sync_with_stdio(false);
    pow2[0]=1;
    circle[0]=1;
    for(int i=1;i<20;i++)
    pow2[i]=pow2[i-1]*2;
    for(int i=1;i<20;i++)
    {
        ll f1=0,f2=1,f3;
        int j;
        for(j=1;;j++)
        {
            f3=(f1%pow2[i]+f2%pow2[i])%pow2[i];
            if(f3==1&&f2==0)
            break;
            f1=f2;
            f2=f3;
        }
        circle[i]=j;
    }
    int n,m;
    while(cin>>n>>m)
    {
    //    cout<<circle[m]<<endl;
        cout<<solve(n,m)<<endl;
    }
    return 0;
}

思路:

找循环节,保存下来即可。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值