Skip to content

Instantly share code, notes, and snippets.

@Rexicon226
Last active November 22, 2025 08:21
Show Gist options
  • Select an option

  • Save Rexicon226/433c151fa0258e662398ffc608d57159 to your computer and use it in GitHub Desktop.

Select an option

Save Rexicon226/433c151fa0258e662398ffc608d57159 to your computer and use it in GitHub Desktop.
const std = @import("std");
const el: u256 = 0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed;
const L = 1 * el;
fn heea(v: u256) struct { u128, u128 } {
std.debug.assert(len(L) == 253);
std.debug.assert(v < L);
std.debug.assert(v > 0);
var r0 = L;
var r1 = v;
var t0: u128 = 0;
var t1: u128 = 1;
const stop_value = len(L) / 2 + 1;
var lenr0 = len(L);
var lenr1 = len(v);
while (lenr1 > stop_value) {
const d = lenr0 - lenr1;
var r: u256 = undefined;
var t: u128 = undefined;
if (r0 >> 255 == r1 >> 255) {
r = r0 -% (r1 << @intCast(d));
t = t0 -% (t1 << @intCast(d));
} else {
r = r0 +% (r1 << @intCast(d));
t = t0 +% (t1 << @intCast(d));
}
if (len(r) > lenr1) {
r0 = r;
t0 = t;
lenr0 = len(r);
} else {
r0 = r1;
r1 = r;
t0 = t1;
t1 = t;
lenr0 = lenr1;
lenr1 = len(r);
}
}
return .{ @truncate(r1), t1 };
}
fn len(l: u256) u256 {
const normalize = l ^ ((l >> 255) * std.math.maxInt(u256));
return 256 - @clz(normalize);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment