hdu 3221 Brute-force Algorithm

Brute-force Algorithm

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1825    Accepted Submission(s): 444


Problem Description
Professor Brute is not good at algorithm design. Once he was asked to solve a path finding problem. He worked on it for several days and finally came up with the following algorithm:

Any fool but Brute knows that the function “funny” will be called too many times. Brute wants to investigate the number of times the function will be called, but he is too lazy to do it.

Now your task is to calculate how many times the function “funny” will be called, for the given a, b and n. Because the answer may be too large, you should output the answer module by P.
 

Input
There are multiple test cases. The first line of the input contains an integer T, meaning the number of the test cases.

For each test cases, there are four integers a, b, P and n in a single line.
You can assume that 1≤n≤1000000000, 1≤P≤1000000, 0≤a, b<1000000.
 

Output
For each test case, output the answer with case number in a single line.
 

Sample Input
  
  
3 3 4 10 3 4 5 13 5 3 2 19 100
 

Sample Output
  
  
Case #1: 2 Case #2: 11 Case #3: 12
 

分析:见hdu4550
#include<cstdio>
#include<cmath>
#define ll __int64
ll a,b,p,n;
struct Matrix{
	ll v[2][2];
};
Matrix A={0,1,1,1},B={1,0,0,1};
ll euler(ll x){
	ll i,ans=x,t=(ll)sqrt(x*10.0);
	for(i=2;i<=t;i++)if(x%i==0){
		ans=ans/i*(i-1);
		while(x%i==0)x/=i;
	}
	if(x>1)ans=ans/x*(x-1);
	return ans;
}
ll quickpow(ll x,ll n){
	ll ans=1;
	while(n){
		if(n&1)ans=ans*x%p;
		n>>=1;
		x=x*x%p;
	}
	return ans;
}
Matrix mul(Matrix m1,Matrix m2,ll M){
	int i,j,k;
	Matrix c;
	for(i=0;i<2;i++)for(j=0;j<2;j++){
		c.v[i][j]=0;
		for(k=0;k<2;k++)c.v[i][j]+=(m1.v[i][k]*m2.v[k][j])%M;
		c.v[i][j]%=M;
	}
	return c;
}
Matrix Mpow(int n,ll M){
	Matrix x=A,c=B;
	while(n>=1){
		if(n&1)c=mul(c,x,M);
		n>>=1;
		x=mul(x,x,M);
	}
	return c;
}
int main(){
	int T,ca=1,i;
	scanf("%d",&T);
	while(T--){
		scanf("%I64d%I64d%I64d%I64d",&a,&b,&p,&n);
		printf("Case #%d: ",ca++);
		if(n==1){printf("%I64d\n",a%p);continue;}
		if(n==2){printf("%I64d\n",b%p);continue;}
		if(n==3){printf("%I64d\n",((a%p)*(b%p))%p);continue;}
		ll phi=euler(p),f1=0,f2=1,f3,aa,bb;bool j=0;
		for(i=4;i<=n;i++){
			f3=f1+f2;
			if(f3>=phi){f3%=phi;j=1;break;}
			f1=f2,f2=f3;
		}
		if(j){
			Matrix res=Mpow(n-3,phi);
			f1=res.v[1][0],f2=res.v[1][1],f3=f1+f2;
			aa=f2%phi+phi,bb=f3%phi+phi;
		}
		else {aa=f3,bb=f1+f2;}
		printf("%I64d\n",(quickpow(a,aa)*quickpow(b,bb))%p);
	}
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值