Skip to content

Instantly share code, notes, and snippets.

@jedisct1
Created January 1, 2022 17:19
Show Gist options
  • Save jedisct1/23c38853005f5dad07abca35dcddcdc2 to your computer and use it in GitHub Desktop.
Save jedisct1/23c38853005f5dad07abca35dcddcdc2 to your computer and use it in GitHub Desktop.
const std = @import("std");
const big = std.math.big;
const Allocator = std.mem.Allocator;
const crypto = std.crypto;
const Managed = big.int.Managed;
const Const = big.int.Const;
const Order = std.math.Order;
fn powMod(res: *Managed, b: Const, e: Const, m: Const) !void {
if (m.eqZero()) {
return error.DivideByZero;
}
const e_abs = e.abs();
const m_abs = m.abs();
if (m_abs.to(u1)) |m_abs_int| {
if (m_abs_int == 1) {
return res.set(0);
}
} else |_| {}
try res.set(1);
var bm = try Managed.init(res.allocator);
var _q = try Managed.init(res.allocator);
try _q.divTrunc(&bm, b, m);
var em = try Managed.init(res.allocator);
try em.copy(e);
while (!em.eqZero()) {
try em.shiftRight(em, 1);
try bm.sqr(bm.toConst());
try _q.divTrunc(&bm, bm.toConst(), m);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment