求解同餘方程組(難度:2顆星)
阿新 • • 發佈:2018-12-21
問題描述:
有一個同餘方程組,有N個同餘方程組成(N由使用者輸入),另外每個同餘方程的a[i]和m[i]也又使用者指定,如下所示:
x≡a[1](mod m[1])
x≡a[2](mod m[2])
x≡a[3](mod m[3])
x≡a[4](mod m[4])
…
x≡a[n](mod m[n])
求x的最小正整數解。
問題分析:
參考我的另外一篇文章“中國剩餘定理”
http://blog.csdn.net/yi_ming_he/article/details/72848318
參考程式碼:
#include <stdio.h>
typedef __int64 int64;
int n, a[100], m[100];//m[100]是mod陣列
int64 ExtendGcd(int64 a, int64 b, int64* px, int64* py)
{
int64 nRet, temp;
if (b == 0)
{
if (px && py)
{
*px = 1;
*py = 0;
}
return a;
}
nRet = ExtendGcd(b, a % b, px, py);
if (px && py)
{
temp = *px ;
*px = *py;
*py = temp - a / b * (*py);
}
return nRet;
}
int64 ChinaRemainder()
{//中國剩餘定理只適合解決m陣列兩兩互質的情況
int64 M = 1, res = 0, x, y, tempM;
int i;
for (i = 0; i < n; i++)
M *= m[i];
for (i = 0; i < n; i++)
{
tempM = M / m[i];
ExtendGcd(tempM, m [i], &x, &y);
res = (res + tempM * x * a[i]) % M;
}
res = (res + M) % M;
return res;
}
int main()
{
scanf_s("%d", &n);//同餘方程組的方程個數
int i;
for (i = 0; i < n; i++)
scanf_s("%d%d", &a[i], &m[i]);
printf("%I64d\n", ChinaRemainder());
return 0;
}
執行結果: