poj 1006+hdu 1788(中国剩余定理求解同余方程组)
2015-01-26 23:38
417 查看
中国剩余定理:
求解此类同余方程组最小非负整数解的算法实现:
poj 1006 Biorhythms
题目链接:http://poj.org/problem?id=1006
解题思路:仔细读题有求解同余方程组 X mod 23 = p (1) 大于d的最小整数解;
X mod 28 = e (2)
X mod 33 = i (3)
因为23,28,33两两互素,满足中国剩余定理的条件,调用函数即可,代码如下:
hdu 1788 Chinese remainder theorem again
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1788
解题思路: N%Mi=Mi-a,即N+a=0(mod Mi)根据中国剩余定理,最小非负整数解一定为0,(或直接根据模结果为0得到)问题所求为Mi的最小公倍数-a
附代码:
求解此类同余方程组最小非负整数解的算法实现:
ll China() { ll M1,ans=0; M=1; for(int i=1;i<=3;i++) M*=m[i]; for(int i=1;i<=3;i++){ M1=M/m[i]; t=extended_gcd(M1,m[i],x,y); ans=(ans+M1*x*a[i])%M; } if(ans<0) ans+=M; return ans; }
poj 1006 Biorhythms
题目链接:http://poj.org/problem?id=1006
解题思路:仔细读题有求解同余方程组 X mod 23 = p (1) 大于d的最小整数解;
X mod 28 = e (2)
X mod 33 = i (3)
因为23,28,33两两互素,满足中国剩余定理的条件,调用函数即可,代码如下:
#include
#include
#include
#include
#include
#include
#include
using namespace std;
typedef long long ll;
const int maxn = 50;
ll p,e,i,d,m[5],a[5],t,x,y,M;
ll extended_gcd(ll a,ll b,ll &x,ll &y)
{
if(b==0) {x=1;y=0;return a;}
ll d=extended_gcd(b,a%b,y,x);
y-=a/b*x;
return d;
}
ll China() { ll M1,ans=0; M=1; for(int i=1;i<=3;i++) M*=m[i]; for(int i=1;i<=3;i++){ M1=M/m[i]; t=extended_gcd(M1,m[i],x,y); ans=(ans+M1*x*a[i])%M; } if(ans<0) ans+=M; return ans; }int main()
{
// freopen("input.txt","r",stdin);
m[1]=23;m[2]=28;m[3]=33;
int count=1;
while(cin>>p>>e>>i>>d&&(p!=-1||e!=-1||i!=-1||d!=-1)){
a[1]=p;a[2]=e;a[3]=i;
ll ans=China();if(ans<=d) ans+=M;
cout<<"Case "<
hdu 1788 Chinese remainder theorem again
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1788
解题思路: N%Mi=Mi-a,即N+a=0(mod Mi)根据中国剩余定理,最小非负整数解一定为0,(或直接根据模结果为0得到)问题所求为Mi的最小公倍数-a
附代码:
#include #include #include #include #include #include #include using namespace std; typedef long long ll; const int maxn = 50; ll k,a,ans,m; ll gcd(ll a,ll b){return b==0?a:gcd(b,a%b);} int main() { // freopen("input.txt","r",stdin); while(cin>>k>>a&&(k||a)){ ans=1; //初始化LCM=1,GCD=0; while(k--){ cin>>m; ans=(ans*m)/gcd(ans,m); } cout<
相关文章推荐
- POJ1006生理周期----【模板】CRT中国剩余定理即孙子定理即求解一次同余方程
- 【中国剩余定理】POJ 1006 & HDU 1370 Biorhythms
- poj 1006 中国剩余定理解同余方程
- 中国剩余定理小结 (互质,非互质) (poj 1006,hdu 3579)
- hdu 1370 || poj 1006 简单的中国剩余定理或者暴力
- 【中国剩余定理】POJ 1006 & HDU 1370 Biorhythms
- poj 2891(中国剩余定理 ------迭代法来求解)
- POJ 1006 中国剩余定理
- hdu 1788 Chinese remainder theorem again 披着中国剩余定理的皮
- POJ1006-Biorhythms .中国剩余定理
- poj1006--中国剩余定理
- poj1006 Biorhythms<中国剩余定理>
- HDU1788 Chinese remainder theorem again 中国剩余定理
- POJ1006: 中国剩余定理的完美演绎(转)
- POJ 1006 Biorhythms --中国剩余定理(互质的)
- poj 1006 Biorhythms 中国剩余定理
- POJ 1006 Biorhythms 中国剩余定理/扩展欧几里得
- POJ 1006 中国剩余定理
- POJ 1006 中国剩余定理?不用那么故弄玄虚吧。。。
- POJ1006 中国剩余定理