UVa10229 - Modular Fibonacci

Problem A: Modular Fibonacci

The Fibonacci numbers (0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...) are defined by the recurrence:

F0 = 0
F1 = 1
Fi = Fi-1 + Fi-2 
for i>1

Write a program which calculates Mn = Fn mod 2m for given pair of n and m0 n 2147483647 and 0 m20. Note that a mod b gives the remainder when a is divided by b.

Input and Output

Input consists of several lines specifying a pair of n and m. Output should be corresponding Mn, one per line.

Sample Input

11 7
11 6

Sample Output

89
25

结果是一个循环数列。也可以用矩阵快速幂做。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <string>
#include <algorithm>
#include <queue>
using namespace std;
vector<int> fib[21];
void init(){
    for(int i = 1; i <= 20; i++){
        int mod = 1<<i;
        int a = 0,b = 1,c = (a+b)%mod;
        fib[i].push_back(a);
        fib[i].push_back(b);
        fib[i].push_back(1%mod);
        while(!(b==0&&c==1)){
            a = b;
            b = c;
            c = (a+b)%mod;
            fib[i].push_back(c);
        }
        fib[i].pop_back();fib[i].pop_back();
    }
}
int main(){

    init();
    int n,m;
    while(cin >> n >> m){
        if(m==0) cout<<0<<endl;
        else   cout<<fib[m][n%fib[m].size()]<<endl;
    }

    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值