POJ1006 Biorhythms-中国剩余定理

题目讲解链接 POJ1006:中国剩余定理的完美演绎

刚开始用的费马小定理求的乘法逆元,一直WA,调了很久才知道费马小定理只能求模数为素数的情况,非素数情况要用欧拉。。

#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
typedef long long ll;
int b[3];			//接收输入 
int n[] = {23,28,33};
int start;		
const int T = 21252;
//扩展欧几里得求乘法逆元 
int ex_gcd(int a,int m,int &x,int &y){
	if(m == 0){
		x = 1;
		y = 0;
		return a;
	}
	int t = ex_gcd(m,a%m,y,x);
	y -= a/m*x;
	return t;
}
//中国剩余定理
int China(int n[],int b[],int mod) {	
	int ret = 0;
	int x,y;	
	for(int i = 0;i < 3;i++){
		int a	= mod / n[i];					
		int tmp = ex_gcd(a,n[i],x,y);		
		ret = (ret + b[i] * a * x) % mod ;		
	}	
	return ret;
}

int main(){
	int CASE = 1;	 	
	while(scanf("%d%d%d%d",&b[0],&b[1],&b[2],&start) != EOF){
		if( b[0] == -1 && b[1] == -1 && b[2] == -1 &&start == -1)
			break;
		int x0;
		x0 = (China(n,b,T)-start+T) % T;        //排除负数情况		
		printf("Case %d: the next triple peak occurs in %d days.\n",CASE++,x0?x0:T);	//注意特判x0==0的情况			
	}
			
	return 0;
}



猜你喜欢

转载自blog.csdn.net/lmhlmh_/article/details/80450387
今日推荐