Chinese remainder theorem again(hdu 1788)两种解法:线性同余方程或者简单的最小公倍数

大概题意:有个最小的N,使得N(mod M[i])=M[i]-a;这里1<=i<=k,1<k<10.就是求出最小的N就行,这里我提供两种思路:

1:线性同余方程的解法:

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long LL;
int n;
int times;
const int MAXN = 1010;
LL A[MAXN], r[MAXN];
LL lcm;
LL gcd(LL a, LL b)
{
    return b == 0? a : gcd(b, a%b);
}
void ex_gcd(LL a, LL b, LL &d, LL &x, LL &y)
{
    if(!b) { d = a; x = 1; y = 0;}
    else { ex_gcd(b, a%b, d, y, x); y -= x*(a/b);}
}
void read_case()
{

}
void solve()
{
    int p;
    while(~scanf("%d%d", &n,&p),n||p)
    {
            lcm = 1;
    for(int i = 1; i <= n; i++)
    {
        scanf("%lld", &A[i]);
        lcm = lcm / gcd(lcm, A[i]) * A[i];
        r[i]=A[i]-p;
    }
//    for(int i = 1; i <= n; i++) scanf("%lld", &r[i]);
    LL a, b, c, d, x, y;
    for(int i = 2; i <= n; i++)
    {
        a = A[1], b = A[i], c = r[i]-r[1];
        ex_gcd(a, b, d, x, y);
        if(c % d) { printf("-1\n"); return ;}
        LL b1 = b / d;
        x *= c / d;
        x = (x%b1 + b1) % b1;
        r[1] = A[1]*x + r[1];
        A[1] = A[1]*(A[i] / d);
    }
    if(r[1] == 0) printf("%lld\n", lcm);
    else printf("%lld\n", r[1]);
    }
}

int main()
{
    int T;
    times = 0;
   solve();
    return 0;
}
第二种解法的分析:

N%M[i]=M[i]-a;

N%M[i]+a=M[i];

(N+a)%M[[i]=0;

就代表N+a就是M[i]的最小公倍数,其中i就是1到k;

下边请见代码实现:

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long LL;
int n;
int times;
const int MAXN = 1010;
LL A[MAXN], r[MAXN];
LL lcm;
LL gcd(LL a, LL b)
{
    return b == 0? a : gcd(b, a%b);
}
int main()
{
    int k,a;
   while(~scanf("%d%d",&n,&k),n||k)
   {
       LL temp=1;
       for(int i=0;i<n;i++)
       {
           scanf("%d",&a);
           temp=(temp/gcd(a,temp))*a;
       }
       printf("%lld\n",temp-k);
   }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值