RosettaCodeData/Task/Modular-exponentiation/D/modular-exponentiation.d

31 lines
769 B
D
Raw Permalink Normal View History

2015-02-20 00:35:01 -05:00
module modular_exponentiation;
2013-04-10 21:29:02 -07:00
2015-02-20 00:35:01 -05:00
private import std.bigint;
BigInt powMod(BigInt base, BigInt exponent, in BigInt modulus)
pure nothrow /*@safe*/ in {
2013-04-10 21:29:02 -07:00
assert(exponent >= 0);
} body {
BigInt result = 1;
2015-02-20 00:35:01 -05:00
while (exponent) {
if (exponent & 1)
2013-04-10 21:29:02 -07:00
result = (result * base) % modulus;
exponent /= 2;
base = base ^^ 2 % modulus;
}
2015-02-20 00:35:01 -05:00
2013-04-10 21:29:02 -07:00
return result;
}
2015-02-20 00:35:01 -05:00
version (modular_exponentiation)
void main() {
import std.stdio;
powMod(BigInt("29883481620585741369158914214988194" ~
"66320163312926952423791023078876139"),
BigInt("235139930337346448646612254452369009" ~
"4744975233415544072992656881240319"),
BigInt(10) ^^ 40).writeln;
}