hzau1202——GCD(斐波那契&矩阵快速幂)

1202: GCD

Time Limit: 1 Sec   Memory Limit: 1280 MB
Submit: 184   Solved: 26
[ Submit][ Status][ Web Board]

Description

Input

 The first line is an positive integer  T . (1<=T<= 10^3) indicates the number of test cases. In the next T lines, there are three positive integer n, m, p (1<= n,m,p<=10^9) at each line.

Output

Sample Input

1 
1 2 3

Sample Output

1


如题所求,其实很简单,只要知道菲波纳契数列前n项和等于第n+2项减1就能轻松AC

先科普一下:

http://blog.sina.com.cn/s/blog_a6f9a3b60102vt3e.html

http://blog.csdn.net/it_beecoder/article/details/52913291

http://blog.csdn.net/xuzengqiang/article/details/7645020

http://blog.csdn.net/qq_15571091/article/details/48528041


#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <cmath>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <stack>
using namespace std;
typedef long long ll;
#define PI 3.1415926535897932
#define E 2.718281828459045
#define INF 0xffffffff//0x3f3f3f3f
#define MAX 10
#define CLR(arr,val) memset(arr,val,sizeof(arr))
#define Bit(n) 1<<n


//const int M=1005;
ll n,m,p;


struct node
{
    int v,w;
    node(int vv,int ww)
    {
        v=vv;
        w=ww;
    }
};
class Matrix{
public:
    Matrix(int r,int c):row(r),col(c){}
    void Init()
    {   CLR(map,0);
        map[0][0]=map[0][1]=map[1][0]=1;
    }
    void Unit() //初始化为单位矩阵
    {   CLR(map,0);
        for(int i=0;i<row;i++)
            map[i][i]=1;
    }
    ll Result() const{return map[0][1]%p;}
    friend Matrix operator*(const Matrix& ,const Matrix&);
    ll Pow(ll);
private:
    ll map[MAX][MAX];
    int row,col;
};
Matrix operator*(const Matrix& M1,const Matrix& M2) //矩阵相乘模板
{   Matrix M(M1.row,M2.col); //相乘之后矩阵的行和列会变化
    for(int i=0;i<M1.row;i++)
        for(int j=0;j<M2.col;j++)
        {   M.map[i][j]=0;
            for(int k=0;k<M1.col;k++)
                M.map[i][j]=(M.map[i][j]+((M1.map[i][k]%p)*(M2.map[k][j]%p))%p)%p;
        }
    return M;
}
Matrix M(2,2);
ll Matrix::Pow(ll n) //矩阵快速幂
{   Matrix temp(2,2);
    temp.Init();
    for(ll i=0;Bit(i)<=n;i++) //利用二进制的思想求解
    {   if(Bit(i)&n) M=M*temp;
        temp=temp*temp;
    }
    return M.Result();
}


ll gcd(ll a,ll b){
    if(b==0)return a;
    else return gcd(b,a%b);
}


int main()
{
    int i,j,k,t;
    int l,g;
    int ans;
    //getpri();
    scanf("%d",&t);
    while(t--)
    {
        M.Unit();
        int num;
        cin>>n>>m>>p;
        //printf("%lld\n",);
        //printf()
       // printf("%d\n",gcd(4,2));
        cout<<M.Pow(gcd(n+2,m+2))%p<<endl;
    }
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值