您的位置:首页 > 大数据 > 人工智能

读控制台HDU 1788 Chinese remainder theorem again 数论读控制台

2013-04-21 01:33 393 查看
发一下牢骚和主题无关:

目题址地: 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;
}

文章结束给大家分享下程序员的一些笑话语录: 爱情观

  爱情就是死循环,一旦执行就陷进去了。

  爱上一个人,就是内存泄露--你永远释放不了。

  真正爱上一个人的时候,那就是常量限定,永远不会改变。

  女朋友就是私有变量,只有我这个类才能调用。

  情人就是指针用的时候一定要注意,要不然就带来巨大的灾难。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: