线性同余方程所有解算法
该解法求出的所有ans均为各解等价类中的代表,可通过加减任意n来得到该等价类的所有解
#include <iostream>
using namespace std;
long ans[1000];
long x,y;
long Extended_GCD(long a,long b)
{
if (b==0)
{
x=1;
y=0;
return a;
}
long d=Extended_GCD(b,a%b);
long t=x;
x=y;
y=t-a/b*y;
return d;
}
long Solove(long a,long b,long n)
{
long d=Extended_GCD(a,n);
if (b%d!=0)
{
return -1;
}
long e=x*(b/d)%n;
long i;
for (i=0;i<d;++i)
{
ans[i]=(e+i*n/d)%n;
}
return d;
}
//ax-ny=b即 ax≡b(mod n)
int main()
{
long a,b,n;
while (scanf("%ld %ld %ld",&a,&b,&n)!=EOF)
{
long len;
if((len=Solove(a,b,n))!=-1)
{
long i;
for (i=0;i<len;++i)
{
printf("%ld\n",ans[i]);
}
}
}
return 0;
}
using namespace std;
long ans[1000];
long x,y;
long Extended_GCD(long a,long b)
{
if (b==0)
{
x=1;
y=0;
return a;
}
long d=Extended_GCD(b,a%b);
long t=x;
x=y;
y=t-a/b*y;
return d;
}
long Solove(long a,long b,long n)
{
long d=Extended_GCD(a,n);
if (b%d!=0)
{
return -1;
}
long e=x*(b/d)%n;
long i;
for (i=0;i<d;++i)
{
ans[i]=(e+i*n/d)%n;
}
return d;
}
//ax-ny=b即 ax≡b(mod n)
int main()
{
long a,b,n;
while (scanf("%ld %ld %ld",&a,&b,&n)!=EOF)
{
long len;
if((len=Solove(a,b,n))!=-1)
{
long i;
for (i=0;i<len;++i)
{
printf("%ld\n",ans[i]);
}
}
}
return 0;
}