HDU-——5451 Best Solver(循环节+矩阵快速幂)

The so-called best problem solver can easily solve this problem, with his/her childhood sweetheart. 
It is known that y=(5+26–√)1+2xy=(5+26)1+2x. 
For a given integer x (0≤x<232)x (0≤x<232) and a given prime number M (M≤46337)M (M≤46337), print [y]%M[y]%M. ([y][y] means the integer part of yy) 

Input

An integer T (1<T≤1000)T (1<T≤1000), indicating there are TT test cases. 
Following are TT lines, each containing two integers xx and MM, as introduced above.

Output

The output contains exactly TT lines. 
Each line contains an integer representing [y]%M[y]%M.

Sample Input

7
0 46337
1 46337
3 46337
1 46337
21 46337
321 46337
4321 46337

Sample Output

Case #1: 97
Case #2: 969
Case #3: 16537
Case #4: 969
Case #5: 40453
Case #6: 10211
Case #7: 17947

题意:已知,给你整数x,和一个素数M,求[y]%M

题解:

首先知道 :循环节题目常见的有两种情况: MOD-1 和  MOD^2-1 通过推导或暴力可求出。

(5+2√6)^n=Xn+Yn*√6 =(Xn-1+Yn-1*√6)*(5+2√6)= 5*Xn-1 + 12*Yn-1 + (2*Xn-1 + 5*Yn-1 )*√6

对应相等得到:

Xn =  5*Xn-1 + 12*Yn-1;广义斐波那契数列形式

Yn =  2*Xn-1 + 5*Yn-1;  广义斐波那契数列形式

所以

注意:(右边括号的X,Y下标应该为n-1),简单矩阵快速幂,不说了~~(这个图是盗的,所以有点错误~~嘻嘻~~) !!!

然而√6还是一个大问题,解决办法:

(5 - 2√6)^n = Xn - Yn*√6

(5+2√6)^n=Xn+Yn*√6 + Xn - Yn*√6 - (Xn - Yn*√6) = 2*Xn - (0.101)^n  这里技巧性很强~

因为 2*Xn-1 < 2*Xn - (0.101)^n  < 2*Xn  所以[ (5+2√6)n ]= 2*Xn - 1

由于n=1+2^x ,求解取模时用到广义斐波那契数列的循环节:(MOD-1)*(MOD+1)

接下来就可以写代码了,上代码:

#include <iostream>
#include <cstring>
using namespace std;
typedef long long ll;
struct hh{
	ll a[20][20];
}x;// 储存构造矩阵以及经过运算得出来的矩阵
hh mul(hh x,hh y,int c){//矩阵快速幂
	hh w;
	memset(w.a,0,sizeof(w.a));
	for (int i = 0; i < 2;i++){
		for (int j = 0; j < 2;j++){
			for (int k = 0; k < 2;k++){
				w.a[i][j]=(w.a[i][j]%c+(x.a[i][k]%c*y.a[k][j]%c)%c)%c;
			}
		}
	}
	return w;
}
hh j_quick(hh a,ll b,ll c){//矩阵快速幂 
	hh ans;
	memset(ans.a,0,sizeof(ans.a));
	for (int i = 0; i < 2;i++){
		ans.a[i][i]=1;
	}
	while(b!=0){
		if(b&1) ans=mul(ans,a,c);
		b>>=1;
		a=mul(a,a,c);
	}
	return ans;
}
ll quick(ll a,ll b,ll c){
	ll ans=1;
	while(b){
		if(b&1) ans=(ans*a)%c;
		b>>=1;
		a=(a*a)%c;
	}
	return ans;
}
int main(){
	int cas=1;
	int t;
	scanf("%d",&t);
	while(t--){
		ll x,m;
		scanf("%d%d",&x,&m);
		hh cao;
		cao.a[0][0]=5;
		cao.a[0][1]=12;
		cao.a[1][0]=2;
		cao.a[1][1]=5;
		ll n=quick(2,x,m*m-1)+1;//循环节在这里用
		hh b = j_quick(cao,n-1,m);
		printf("Case #%d: %lld\n",cas++,(2*(5*b.a[0][0]+2*b.a[0][1])-1)%m);
	}
	return 0;
} 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

心脏dance

如果解决了您的疑惑,谢谢打赏呦

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值