ZOJ 3609 Modular Inverse
你可以用拓展欧几里德,但实际上一个for就ok了
#include <stdio.h>
int gcd(int a,int b)
{
int r = a;
while(a = r % b) {
r = b;
b = a;
}
return b;
}
int main()
{
int T,a,m,i;
scanf("%d",&T);
while(T--) {
scanf("%d%d",&a,&m);
if(m == 1)
puts("1");
else if(gcd(a,m) != 1)
puts("Not Exist");
else {
for(i = 1;(a * i) % m != 1;i++);
printf("%d\n",i);
}
}
}
拓展欧几里德
#include <stdio.h>
int x,y,t,r;
int exgcd(int a,int b)
{
if (b == 0) {
x = 1;
y = 0;
return a;
}
r = exgcd(b,a % b);
t = x;
x = y;
y = t - a / b * y;
return r;
}
int main()
{
int T,a,m,i;
scanf("%d",&T);
while(T--) {
scanf("%d%d",&a,&m);
if(exgcd(a,m) != 1)
puts("Not Exist");
else
printf("%d\n",x > 0? x: x + m);
}
}