题目地址: http://acm.hdu.edu.cn/showproblem.php?pid=1788
N除以M1余(M1 - a),除以M2余(M2-a), 除以M3余(M3-a),总之, 除以MI余(MI-a)
求最小的N。
第一种解法:直接按题意做(孙子定理)
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <queue>
using namespace std;
/*
freopen("input.txt", "r", stdin); //读数据
freopen("output.txt", "w", stdout); //注释掉此句则输出到控制台
*/
typedef __int64 LL;
LL w[15],b[15];
int n;
//扩展Euclid求解gcd(a,b)=ax+by
LL ext_gcd(LL a,LL b,LL& x,LL& y)
{
LL t,ret;
if (!b)
{
x=1,y=0;
return a;
}
ret=ext_gcd(b,a%b,x,y);
t=x,x=y,y=t-a/b*y;
return ret;
}
LL China_left2()
{
LL w1,w2,b1,b2,gcd,x,y,t;
int i,flag;
flag=0;w1=w[0];b1=b[0];
for(i=1;i<n;i++)
{
w2=w[i];b2=b[i];
gcd=ext_gcd(w1,w2,x,y);
if((b2-b1)%gcd)
{
flag=1;break;
}
t=w2/gcd;
x=(x*(b2-b1))/gcd;
x=(x%t+t)%t;
b1=w1*x+b1;
w1=(w1*w2)/gcd;
b1=(b1%w1+w1)%w1;
}
if(flag==1)
b1=-1;
if(b1==0&&n>1)
b1=w1;
if(b1==0&&n==1)
b1=w[0];
return b1;
}
int main()
{
int i,a;
while(cin>>n>>a&&n+a)
{
for(i=0;i<n;i++)
{
scanf("%I64d",&w[i]);
b[i]=w[i]-a;
}
printf("%I64d\n",China_left2());
}
return 0;
}
求M1、M2、、、Mn的最小公倍数,然后lcm-a,因为都是余a嘛。
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <queue>
using namespace std;
/*
freopen("input.txt", "r", stdin); //读数据
freopen("output.txt", "w", stdout); //注释掉此句则输出到控制台
*/
typedef __int64 LL;
LL w[11];
LL gcd(LL m,LL n)//最大公约数
{
LL t;
while(n)
{ t=m%n; m=n; n=t; }
return m;
}
int main()
{
int i,a,n;
while(cin>>n>>a&&n+a)
{
LL xiaohao=1;
for(i=0;i<n;i++)
{
scanf("%I64d",&w[i]);
xiaohao=(xiaohao/gcd(xiaohao,w[i])*w[i]);
}
printf("%I64d\n",xiaohao-a);
}
return 0;
}