Index: sdk/lib/_internal/compiler/js_lib/js_number.dart |
diff --git a/sdk/lib/_internal/compiler/js_lib/js_number.dart b/sdk/lib/_internal/compiler/js_lib/js_number.dart |
index 8ea8a0326c694c326f07ceb8922073e3331b887b..0c13b8f11d2ed98b897ff1aee64eac884756020b 100644 |
--- a/sdk/lib/_internal/compiler/js_lib/js_number.dart |
+++ b/sdk/lib/_internal/compiler/js_lib/js_number.dart |
@@ -411,6 +411,64 @@ class JSInt extends JSNumber implements int, double { |
return r; |
} |
+ // Returns 1/this % m, with m > 0. |
+ int modInverse(int m) { |
+ if (m is! int) throw new ArgumentError(m); |
+ if (m <= 0) throw new RangeError(m); |
+ if (m is _Bigint) { |
+ return _toBigint().modInverse(m); |
+ } |
+ bool ac = m.isEven; |
+ int u = m; |
+ int v = this; |
+ int a = 1, |
+ b = 0, |
+ c = 0, |
+ d = 1; |
+ while (u != 0) { |
+ while (u.isEven) { |
+ u ~/= 2; |
+ if (ac) { |
+ if (!a.isEven || !b.isEven) { |
+ a += this; |
+ b -= m; |
+ } |
+ a ~/= 2; |
+ } else if (!b.isEven) { |
+ b -= m; |
+ } |
+ b ~/= 2; |
+ } |
+ while (v.isEven) { |
+ v ~/= 2; |
+ if (ac) { |
+ if (!c.isEven || !d.isEven) { |
+ c += this; |
+ d -= m; |
+ } |
+ c ~/= 2; |
+ } else if (!d.isEven) { |
+ d -= m; |
+ } |
+ d ~/= 2; |
+ } |
+ if (u >= v) { |
+ u -= v; |
+ if (ac) a -= c; |
+ b -= d; |
+ } else { |
+ v -= u; |
+ if (ac) c -= a; |
+ d -= b; |
+ } |
+ } |
+ if (v != 1) return 0; |
+ if (d > m) return d - m; |
+ if (d < 0) d += m; |
+ if (d < 0) d += m; |
+ return d; |
+ } |
+ |
// Assumes i is <= 32-bit and unsigned. |
static int _bitCount(int i) { |
// See "Hacker's Delight", section 5-1, "Counting 1-Bits". |