Modular inversion: computes a^(-1) mod p Requires gcd(a,p) = 1. The result is normalized to the range [0, p).
fn modularInverse(comptime T: type, comptime a: T, comptime p: T) T
fn modularInverse(comptime T: type, comptime a: T, comptime p: T) T {
// Use a signed type for EEA computation
const type_info = @typeInfo(T);
const SignedT = if (type_info == .int and type_info.int.signedness == .unsigned)
@Int(.signed, type_info.int.bits)
else
T;
const a_signed = @as(SignedT, @intCast(a));
const p_signed = @as(SignedT, @intCast(p));
const r = extendedEuclidean(SignedT, a_signed, p_signed);
assert(r.gcd == 1);
// Normalize result to [0, p)
var result = r.x;
while (result < 0) {
result += p_signed;
}
return @intCast(result);
}