/* reduce this mod m */ public virtual void Mod(BIG m1) { int k = 0; BIG r = new BIG(0); BIG m = new BIG(m1); Norm(); if (Comp(this, m) < 0) { return; } do { m.FShl(1); k++; } while (Comp(this, m) >= 0); while (k > 0) { m.FShr(1); r.Copy(this); r.Sub(m); r.Norm(); CMove(r, (int)(1 - ((r.w[NLEN - 1] >> (CHUNK - 1)) & 1))); k--; } }
/* divide this by m */ public virtual void Div(BIG m1) { int d, k = 0; Norm(); BIG e = new BIG(1); BIG m = new BIG(m1); BIG b = new BIG(this); BIG r = new BIG(0); Zero(); while (Comp(b, m) >= 0) { e.FShl(1); m.FShl(1); k++; } while (k > 0) { m.FShr(1); e.FShr(1); r.Copy(b); r.Sub(m); r.Norm(); d = (int)(1 - ((r.w[NLEN - 1] >> (CHUNK - 1)) & 1)); b.CMove(r, d); r.Copy(this); r.Add(e); r.Norm(); CMove(r, d); k--; } }
/* this=1/this mod p. Binary method */ public virtual void InvModp(BIG p) { Mod(p); BIG u = new BIG(this); BIG v = new BIG(p); BIG x1 = new BIG(1); BIG x2 = new BIG(0); BIG t = new BIG(0); BIG one = new BIG(1); while (Comp(u, one) != 0 && Comp(v, one) != 0) { while (u.Parity() == 0) { u.FShr(1); if (x1.Parity() != 0) { x1.Add(p); x1.Norm(); } x1.FShr(1); } while (v.Parity() == 0) { v.FShr(1); if (x2.Parity() != 0) { x2.Add(p); x2.Norm(); } x2.FShr(1); } if (Comp(u, v) >= 0) { u.Sub(v); u.Norm(); if (Comp(x1, x2) >= 0) { x1.Sub(x2); } else { t.Copy(p); t.Sub(x2); x1.Add(t); } x1.Norm(); } else { v.Sub(u); v.Norm(); if (Comp(x2, x1) >= 0) { x2.Sub(x1); } else { t.Copy(p); t.Sub(x1); x2.Add(t); } x2.Norm(); } } if (Comp(u, one) == 0) { Copy(x1); } else { Copy(x2); } }