Skip to content

Commit dfc3d02

Browse files
Aditya-132ibuclaw
andauthored
Fix #10513 - powmod is slow for ulong (#10688)
Co-authored-by: Iain Buclaw <[email protected]>
1 parent 89f5914 commit dfc3d02

File tree

1 file changed

+27
-16
lines changed

1 file changed

+27
-16
lines changed

std/math/exponential.d

+27-16
Original file line numberDiff line numberDiff line change
@@ -830,28 +830,39 @@ if (isUnsigned!F && isUnsigned!G && isUnsigned!H)
830830
{
831831
static if (T.sizeof == 8)
832832
{
833-
static T addmod(T a, T b, T c)
833+
if (c <= 0x100000000)
834834
{
835-
b = c - b;
836-
if (a >= b)
837-
return a - b;
838-
else
839-
return c - b + a;
835+
T result = a * b;
836+
return result % c;
840837
}
838+
else
839+
{
840+
import core.int128 : Cent, mul, udivmod;
841841

842-
T result = 0, tmp;
842+
auto product = mul(a, b);
843843

844-
b %= c;
845-
while (a > 0)
846-
{
847-
if (a & 1)
848-
result = addmod(result, b, c);
844+
if (product.hi >= c)
845+
{
846+
product.hi %= c;
847+
}
849848

850-
a >>= 1;
851-
b = addmod(b, b, c);
849+
T remainder = void;
850+
udivmod(product, c, remainder);
851+
return remainder;
852+
}
853+
}
854+
else static if (T.sizeof == 4)
855+
{
856+
if (c <= 0x10000)
857+
{
858+
T result = a * b;
859+
return result % c;
860+
}
861+
else
862+
{
863+
DoubleT result = cast(DoubleT) (cast(DoubleT) a * cast(DoubleT) b);
864+
return result % c;
852865
}
853-
854-
return result;
855866
}
856867
else
857868
{

0 commit comments

Comments
 (0)