Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(263)

Unified Diff: sdk/lib/_internal/compiler/js_lib/js_number.dart

Issue 1174513004: Implement modInverse (bigint version does not support even modulus yet). (Closed) Base URL: git@github.com:dart-lang/sdk.git@master
Patch Set: Address review comments Created 5 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
« no previous file with comments | « runtime/lib/integers.dart ('k') | sdk/lib/core/int.dart » ('j') | no next file with comments »
Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
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".
« no previous file with comments | « runtime/lib/integers.dart ('k') | sdk/lib/core/int.dart » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698