Elegant fibonacci numbers again

Elegant fibonacci numbers again

Time Limit : 3000/1000ms (Java/Other)   Memory Limit : 65535/32768K (Java/Other)

Total Submission(s) : 15   Accepted Submission(s) : 3

Font: Times New Roman | Verdana | Georgia

Font Size: ← →

Problem Description

Fibonacci numbers are nice simple integers. All of you are familiar with it, arent you?
The Fibonacci sequence <F[n]> are defined by the recurrence:
F[0]=0;
F[1]=1;
F[n]=F[n-1]+F[n-2], for n>1
You know that the value of F[n] increases rapidly when the n becomes larger. So for each test case,output the value F[n] mod m will be ok.

Input

The first line of the input is a positive integer.It is the number of the test cases followed. Each test case contains two integers n (0<=n<2^32) and m (0<m<10000). There may be one or several spaces between the two integers.

Output

The output of the program should consist of one line of output for each test case.The output of each test case only contains one integer which equals to the value F[n] mod m. No any redundant spaces are needed.

Sample Input

2

1 1000

2 100

Sample Output

1

 

 

#include<cstdio>

struct node
{
	int f[2][2];
};

node mul(node a,node b,int mod)//矩阵相乘
{
	node ret;
	ret.f[0][0]=(a.f[0][0]*b.f[0][0]+a.f[0][1]*b.f[1][0])%mod;
	ret.f[0][1]=(a.f[0][0]*b.f[0][1]+a.f[0][1]*b.f[1][1])%mod;
	ret.f[1][0]=(a.f[1][0]*b.f[0][0]+a.f[1][1]*b.f[1][0])%mod;
	ret.f[1][1]=(a.f[1][0]*b.f[0][1]+a.f[1][1]*b.f[1][1])%mod;
    return ret;
}

node mypow(node x,int e,int mod)//矩阵幂取模
{
	node ret,temp;
	if(e==0)
	{
		x.f[0][0]=1; x.f[0][1]=0;
		x.f[1][0]=0; x.f[1][1]=1;
	}
	if(e==1) return x;
	temp=mypow(x,e/2,mod);//二分求矩阵幂  x^e=x^(e/2)*x^(e^2);
	ret=mul(temp,temp,mod);
	if(e%2==1) ret=mul(ret,x,mod);//如果e是奇数,那还需要乘以x
	return ret;
}

int main()
{
	int t,n,m;
	node x;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d %d",&n,&m);
		x.f[0][0]=1; x.f[0][1]=1;
		x.f[1][0]=1; x.f[1][1]=0;
		if(n)
		{
		x=mypow(x,n-1,m);//算出初始矩阵的n-1次方  然后相乘
		printf("%d\n",x.f[0][0]);//即为 f[n];
		}
		else printf("0\n");
	}
	return 0;
}


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值