public static MutableInteger SetModularInversePowerOfTwoModulus(this MutableInteger c, MutableInteger d, int n, MutableIntegerStore store) { // See 9.2 in: http://gmplib.org/~tege/divcnst-pldi94.pdf c.Set(d); var two = store.Allocate().Set(2); var reg1 = store.Allocate(); var reg2 = store.Allocate(); for (int m = 3; m < n; m *= 2) { reg1.Set(c); reg2.SetProduct(reg1, d); reg2.Mask(n); reg2.SetDifference(two, reg2); c.SetProduct(reg1, reg2); c.Mask(n); } if (c.Sign == -1) { c.Add(reg1.Set(1).LeftShift(n)); } store.Release(two); store.Release(reg1); store.Release(reg2); return(c); }