int Inverse(int x, int y)
{
return x!=1?(1+(x-1)*Inverse(y%x,x)%x*y)/x:1;
}
I think it can be transformed into easier-to-read code:
Firstly, replace
(x-1)*Inverse(y%x,x)%x*y
by
(x-Inverse(y%x,x))%x*y
which gets rid of the (x-1) which confuses the code a bit.
Fortunatley it also gets rid of a multiply.
For an inverse to be defined in Inverse(x,y), x must not be 0, as will its inverse
and therefore we can assume that Inverse(a,x) returns a number in [1..x), and
therefore (x-Inverse(y%x,x)) is in [1..x) too, and therefore the %x is elidable.
For readability I'd reverse teh sense of the ?: too.
int Inverse(int x, int y)
{
return x==1?1:(1+(x-Inverse(y%x,x))*y)/x;
}
Which reduces the op count quite a bit (5 to 3), and is more readable.
Whether it works is another matter, I'm writing this on the fly, just from
cursory inspection!
Phil
CRT: r = a (mod y) => r = a + (b-a) y (1/y mod x)
r = b (mod x)
-> xz = 1 (mod y) => xz = 1 + (0-1) y (1/y mod x)
xz = 0 (mod x)
=> z = 1/x (1 - y (1/y mod x))
-Bill Dubuque