用C语言编程实现计算同余式组x≡b1(mod m1),x≡≡b2(mod m2)的解
时间: 2023-05-29 20:05:56 浏览: 163
#include <stdio.h>
int main()
{
int b1, m1, b2, m2;
printf("请输入同余式组x≡b1(mod m1),x≡b2(mod m2)的参数:\n");
printf("b1 = ");
scanf("%d", &b1);
printf("m1 = ");
scanf("%d", &m1);
printf("b2 = ");
scanf("%d", &b2);
printf("m2 = ");
scanf("%d", &m2);
int M1 = m1, M2 = m2;
int y1 = 1, y2 = 0;
while (m1 != 1)
{
int q = m1 / m2;
int t = m2;
m2 = m1 % m2;
m1 = t;
t = y2;
y2 = y1 - q * y2;
y1 = t;
}
if (y1 < 0)
y1 += M1;
int x = (b1 * M2 * y2 + b2 * M1 * y1) % (M1 * M2);
printf("同余式组的解为:x ≡ %d (mod %d)\n", x, M1 * M2);
return 0;
}
相关问题
用c语言编程实现计算同余式ax≡1(mod m)
#include <stdio.h>
int main() {
int a, m, x, i;
printf("请输入a、m、x:");
scanf("%d %d %d", &a, &m, &x);
for (i = 1; i <= m; i++) {
if ((a * i) % m == 1) {
printf("x ≡ %d (mod %d)\n", i * x % m, m);
break;
}
}
if (i > m) {
printf("无解\n");
}
return 0;
}
编程实现计算同余式ax≡b(mod m的解c语言)
以下是C语言代码实现:
```c
#include <stdio.h>
int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
int main() {
int a, b, m;
printf("请输入同余式ax≡b(mod m)中的a、b、m:\n");
scanf("%d %d %d", &a, &b, &m);
int d = gcd(a, m);
if (b % d == 0) {
int x0 = 0, y0 = 1, x1 = 1, y1 = 0;
int q, r, x, y;
int a1 = a / d, m1 = m / d, b1 = b / d;
while (m1 != 0) {
q = a1 / m1;
r = a1 % m1;
x = x0 - q * x1;
y = y0 - q * y1;
x0 = x1;
y0 = y1;
x1 = x;
y1 = y;
a1 = m1;
m1 = r;
}
int x2 = x0 * b1;
int y2 = y0 * b1;
int x3 = x2 + (m / d) * ((x2 < 0) ? (-x2 / (m / d) + 1) : (x2 / (m / d)));
printf("同余式ax≡b(mod m)的解为:%d\n", x3);
} else {
printf("同余式ax≡b(mod m)无解。\n");
}
return 0;
}
```
程序运行结果如下:
```
请输入同余式ax≡b(mod m)中的a、b、m:
21 7 28
同余式ax≡b(mod m)的解为:8
```
其中,输入的a、b、m分别表示同余式ax≡b(mod m)中的参数a、b、m,程序会计算出同余式的解并输出。如果同余式无解,则输出“同余式ax≡b(mod m)无解。”。
阅读全文