欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

递归组织-P1188 :斐波那契数列(2)

最编程 2024-07-02 15:09:19
...

题目描述

菲波那契数列是指这样的数列:数列的第一一个和第二个数都为1,接下来每个数都等于前面2个数之和。给出一一个正整数a,要求菲波那契数列中第a个数对1000取模的结果是多少。

【输入】

第1行是测试数据的组数n,后面跟着n行输入。每组测试数据占1行,包括一个正整数a(1≤a≤100000)。

【输出】

n行,每行输出对应一一个输入。输出应是一个正整数,为菲波那契数列中第a个数对1000取模得到的结果。

【输入样例】

4
5
2
19
1

【输出样例】

5
1
181
1

思路

这个题我巩固了一下矩阵乘法。

代码

#include "iostream"
#include "cstdio"
#include "algorithm"
#include "cstring"
#include "string"
#include "cmath"
#define int long long
using namespace std;

const int p = 1000;
int n,a,b;

struct matrix{
    int a[4][4]={};
    void print(){
        for(int i = 0;i < 2; i++){
            for(int j = 0;j < 2; j++){
                cout << a[i][j] << ' ';
            }
            cout << endl;
        }
    } 
}in,e;

matrix operator *(matrix &a,matrix &b){
        matrix c;
        for(int i = 0;i < 2; i++){
            for(int j = 0;j < 2; j++){
                for(int k = 0;k < 2; k++){
                    (c.a[i][j] += a.a[i][k] * b.a[k][j] %p) %=p;
                }
            }
        }
        return c;
}

matrix Pow(matrix a,int x){
    matrix tot = e;
    while(x){
        if(x & 1) tot = a * tot;
        a = a * a;
        x >>= 1;
    }
    return tot;
}

signed main(){
    int t;
    cin >> t;
    while(t--){
        cin >> n ;
        a = 1,b = 1; 
        
        e.a[0][0] = 1;e.a[0][1] = 1;
        
        in.a[0][0] = 0; in.a[0][1] = b;
        in.a[1][0] = 1; in.a[1][1] = a;

        matrix ans = Pow(in,n);
        
        int x = ans.a[1][1];
        cout << x << endl;
        }
    return 0;
}