I've found this snippet in the guts of GCC compiler. This is modulo inverse.
/* Computes inverse to X modulo (1 << MOD). */
static uint64_t
inverse (uint64_t x, int mod)
{
uint64_t mask =
((uint64_t) 1 << (mod - 1) << 1) - 1;
uint64_t rslt = 1;
int i;
for (i = 0; i < mod - 1; i++)
{
rslt = (rslt * x) & mask;
x = (x * x) & mask;
}
return rslt;
}
https://github.com/gcc-mirror/gcc/blob/1cb6c2eb3b8361d850be8e8270c597270a1a7967/gcc/loop-iv.c#L1291
And it works. But how? This is obviously not extended euclidian algorithm. Am I correct that a product of quadratic residues is computed here?
Where to read more about this method?