中国剩余定理

中国剩余定理用于求解多个模方程的解,即:x = a[i] mod(b[i])(其中b[i]要求两两互质);类似于韩信点兵类的问题。

令N = b[0]*b[1]*b[2].....b[n]; 则在模N的剩余系中,方程有唯一解。

中国剩余定理模板题目poj1006;

#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<climits>
#include<cctype>
#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
#include<map>
#include<set>
#include<string>
#include<stack>
#define ll long long
#define MAX 1000
#define INF INT_MAX
#define eps 1e-6

using namespace std;

void ex_gcd(ll a, ll b, ll& x, ll& y){      //扩展的欧几里得算法求模方程的一个解x 
	if (b == 0){
		x = 1;
		y = 0;
		return;
	}
	ex_gcd(b, a%b, y,x);
	y -= x * (a / b);
}

ll a[10],d;
ll b[] = {23,28,33};

ll china(int n){                       //中国剩余定理,求最小整数解 ans = (ans + N) % N(模N下的唯一解); 
	ll N = 1;
	ll ans = 0;
	for (int i=0; i<n; i++) N *= b[i];
	ll x,y;
	for (int i=0; i<n; i++){
		ll u = N / b[i];
		ex_gcd(u,b[i],x,y);
		ans = (ans + x*u*a[i]) % N;
	}
	if (ans - d > 0) return ans - d;
	else return ans - d + N;
}

int main(){
	int cas = 0;
	while (scanf("%lld%lld%lld%lld",&a[0],&a[1],&a[2],&d) && d >= 0){
		cas++;
		printf("Case %d: the next triple peak occurs in %lld days.\n",cas,china(3));
	}
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值