-
Notifications
You must be signed in to change notification settings - Fork 0
/
ModExp.m
43 lines (36 loc) · 1.05 KB
/
ModExp.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
function result = ModExp(base, exp, m)
% Modular exponentiation (powermod)
% result = base ^ exp (mod m)
% private function which does minimal input validation
if m == 0
result = base ^ exp;
return;
end
origCls = class(base);
if base < 0
% make base positive by adding multiple of m
multiple = floor(-base / m) + 1;
base = base + multiple * m;
assert(base >= 0);
end
base = uint64(base);
exp = uint64(exp);
m = uint64(m);
if exp == 2 && base <= 4294967295
% squaring is common enough to special case
% 4294967295 is max number which does not overflow uint64 when squared
result = mod(base * base, m);
return;
end
result = 1;
base = mod(base, m);
% exponentiation by squaring
while exp > 0
if bitand(exp, 1) % odd numbers
result = ModMultiply(result, base, m);
end
base = ModMultiply(base, base, m);
exp = bitshift(exp, -1);
end
result = cast(result, origCls);
end