Skip to content

Commit df96127

Browse files
committed
More optimization friendly expression.
1 parent 3c55282 commit df96127

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed

lib/std/math/egcd.zig

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ inline fn egcd_helper(other: anytype, odd: anytype, shift: anytype) [3]@TypeOf(o
1919
const S = @TypeOf(other, odd);
2020
const toinv = @shrExact(other, @intCast(shift));
2121
const ctrl = @shrExact(odd, @intCast(shift)); // Invariant: |s|, |t|, |ctrl| < |MIN_OF(S)|
22-
const hctrl = 1 + @shrExact(ctrl - 1, 1);
22+
const half_ctrl = 1 + @shrExact(ctrl - 1, 1);
2323

2424
var s: S = std.math.sign(toinv);
2525
var t: S = 0;
@@ -31,9 +31,11 @@ inline fn egcd_helper(other: anytype, odd: anytype, shift: anytype) [3]@TypeOf(o
3131
const xz = @ctz(x);
3232
x = @shrExact(x, @intCast(xz));
3333
for (0..xz) |_| {
34-
const s_odd = s & 1 != 0;
35-
s = @divFloor(s, 2);
36-
if (s_odd) s += hctrl;
34+
const half_s = @divFloor(s, 2);
35+
if (s & 1 == 0)
36+
s = half_s
37+
else
38+
s = half_s + half_ctrl;
3739
}
3840
}
3941

@@ -55,9 +57,11 @@ inline fn egcd_helper(other: anytype, odd: anytype, shift: anytype) [3]@TypeOf(o
5557
}
5658
x = @shrExact(x, @intCast(xz));
5759
for (0..xz) |_| {
58-
const s_odd = s & 1 != 0;
59-
s = @divFloor(s, 2);
60-
if (s_odd) s += hctrl;
60+
const half_s = @divFloor(s, 2);
61+
if (s & 1 == 0)
62+
s = half_s
63+
else
64+
s = half_s + half_ctrl;
6165
}
6266
}
6367

0 commit comments

Comments
 (0)