poj 1006+hdu 1788(中国剩余定理求解同余方程组)

中国剩余定理:


求解此类同余方程组最小非负整数解的算法实现:

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 "< 
          
            <<": the next triple peak occurs in "< 
           
             <<" days."< 
             
            
           
          
         
       
     
     
    
    
   
   

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< 
           
             < 
             
            
           
          
        
      
      
     
     
    
    




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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值