Modular exponentiation: computes a^s mod p using square-and-multiply algorithm.
fn modularPow(comptime T: type, comptime a: T, s: T, comptime p: T) T
fn modularPow(comptime T: type, comptime a: T, s: T, comptime p: T) T {
const type_info = @typeInfo(T);
const bits = type_info.int.bits;
const WideT = @Int(.unsigned, bits * 2);
var ret: T = 1;
var base: T = a;
var exp = s;
while (exp > 0) {
if (exp & 1 == 1) {
ret = @intCast((@as(WideT, ret) * @as(WideT, base)) % p);
}
base = @intCast((@as(WideT, base) * @as(WideT, base)) % p);
exp >>= 1;
}
return ret;
}