使用 C# 语言进行模 m 幂的计算:
namespace Skyiv.Utils
{
public static class ModPowExtensions
{
public static int ModPow(this int a, int b, int m)
{
long v = 1;
for (long c = a; b != 0; b >>= 1, c = c * c % m)
if ((b & 1) != 0) v = v * c % m;
return (int)v;
}
}
}
D:\>clang++ p593b.cpp -O2
p593b.cpp:59:17: warning: & has lower precedence than >; > will be evaluated first [-Wparentheses]
if (exp & 1 > 0) result = (result * base) % m;
^~~~~~~
p593b.cpp:59:17: note: place parentheses around the '>' expression to silence this warning
if (exp & 1 > 0) result = (result * base) % m;
^
( )
ll modpow(ll base,ll exp,ll m)
{
ll result=1;
while (exp > 0)
{
if (exp & 1 > 0) result = (result * base) % m;
exp >>= 1;
base = (base * base) % m;
}
return result;
}