poj2891(中国剩余定理)
2013-07-29 09:46
134 查看
点击打开链接
//满足x%a1=r1,x%a2=r2,..x%an%rn,求x
//因为a1,a2..不互质,不能用剩余定理
//只能一步一步计算
/*关键:
x=((r/d*x)%t+t)%t;t=a2/d;
r1=x*a1+r1;
a1=a1*a2/d;
*/
#include"stdio.h"
#include"string.h"
typedef __int64 LL;
LL x,y,d;
void exgcd(LL a,LL b)
{
if(b==0)
{
x=1;y=0;d=a;
}
else
{
exgcd(b,a%b);
LL t=x;
x=y;
y=t-(a/b)*y;
}
}
int main()
{
LL n;
LL a1,a2;
LL r1,r2;
LL flag,i;
while(scanf("%I64d",&n)!=-1)
{
scanf("%I64d%I64d",&a1,&r1);
flag=0;
for(i=0;i<n-1;i++)
{
scanf("%I64d%I64d",&a2,&r2);
LL r=r2-r1;
exgcd(a1,a2);
if(r%d!=0)
{
flag=1;continue;
}
LL t=a2/d;
x=((r/d*x)%t+t)%t;
r1=x*a1+r1;
a1=a1*a2/d;
}
if(flag==1)printf("-1\n");
else printf("%I64d\n",r1);
}
return 0;
}
//满足x%a1=r1,x%a2=r2,..x%an%rn,求x
//因为a1,a2..不互质,不能用剩余定理
//只能一步一步计算
/*关键:
x=((r/d*x)%t+t)%t;t=a2/d;
r1=x*a1+r1;
a1=a1*a2/d;
*/
#include"stdio.h"
#include"string.h"
typedef __int64 LL;
LL x,y,d;
void exgcd(LL a,LL b)
{
if(b==0)
{
x=1;y=0;d=a;
}
else
{
exgcd(b,a%b);
LL t=x;
x=y;
y=t-(a/b)*y;
}
}
int main()
{
LL n;
LL a1,a2;
LL r1,r2;
LL flag,i;
while(scanf("%I64d",&n)!=-1)
{
scanf("%I64d%I64d",&a1,&r1);
flag=0;
for(i=0;i<n-1;i++)
{
scanf("%I64d%I64d",&a2,&r2);
LL r=r2-r1;
exgcd(a1,a2);
if(r%d!=0)
{
flag=1;continue;
}
LL t=a2/d;
x=((r/d*x)%t+t)%t;
r1=x*a1+r1;
a1=a1*a2/d;
}
if(flag==1)printf("-1\n");
else printf("%I64d\n",r1);
}
return 0;
}
相关文章推荐
- poj2891 Strange Way to Express Integers(中国剩余定理)
- poj2891 Strange Way to Express Integers (中国剩余定理+拓展欧几里得)
- poj2891 Strange Way to Express Integers(中国剩余定理)
- POJ2891 Strange Way to Express Integers(中国剩余定理)
- [poj2891]Strange Way to Express Integers(扩展中国剩余定理)
- [POJ2891]Strange Way to Express Integers(扩展中国剩余定理)
- HDU1370(中国剩余定理)
- fzu 1402 猪的安家 (中国剩余定理)
- Light Oj 1319 (中国剩余定理)
- codeforces 687B - Remainders Game 数学相关(互质中国剩余定理)
- lightoj 1319 Monkey Tradition(中国剩余定理)
- hdu1006Biorhythms(中国剩余定理)
- 【中国剩余定理-非互质】POJ2891[Strange Way to Express Integers]题解
- [模板] 中国剩余定理
- POJ 1006 Biorhythms (中国剩余定理)
- POJ 题目1006 Biorhythms(中国剩余定理)
- 【POJ2891】Strange Way to Express Integers 中国剩余定理
- 孙子定理(中国剩余定理)
- [Codeforces710D]Two Arithmetic Progressions(扩展中国剩余定理)
- 中国剩余定理