 php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login go to bug id or search bugs for
Bug #25328 Submitted: modulus operator problem with large numbers 2003-08-30 18:39 UTC 2003-08-31 03:00 UTC hakon at haugnes dot name Not a bug *Math Functions 4.3.2 Redhat 8.0 No None
[2003-08-30 18:39 UTC] hakon at haugnes dot name
```Description:
------------
The modulus operator % returns wrong results if the number gets large. In a program used to calculate primes, it will find that large numbers, ending in 5, are prime. The following are calculations using % on such a large number, note that all numbers used in the MOD calculation are whole integers (and should not suffer rounding by MOD):

MOD: 53253252355 % 3=1
DIV: 53253252355 / 3=17751084118.333332061767578125

MOD: 53253252355 % 4=3
DIV: 53253252355 / 4=13313313088.75

MOD: 53253252355 % 5=2
DIV: 53253252355 / 5=10650650471

Obviously, any number ending in 5 cannot be prime, since it will always be divisible by 5. The MOD result on 5 is therefore wrong, as the division proves.

Reproduce code:
---------------
\$i=53253252355;
ini_set("precision",35);

for (\$m=2; \$m<=\$i; \$m++){
echo "MOD: \$i % \$m=". \$i % \$m ;
echo "DIV: \$i / \$m=". \$i/\$m ."<Br>";
}

Expected result:
----------------
I would expect to see

MOD: 53253252355 % 3=1
DIV: 53253252355 / 3=17751084118.333332061767578125
MOD: 53253252355 % 4=3
DIV: 53253252355 / 4=13313313088.75
MOD: 53253252355 % 5=0
DIV: 53253252355 / 5=10650650471

Actual result:
--------------

MOD: 53253252355 % 3=1
DIV: 53253252355 / 3=17751084118.333332061767578125
MOD: 53253252355 % 4=3
DIV: 53253252355 / 4=13313313088.75
MOD: 53253252355 % 5=2 [THE ERROR]
DIV: 53253252355 / 5=10650650471

```

## Pull Requests

```I just realized that the [mal]functioning of % for large numbers is probably why the function BCMOD has been created...
```It's not a malfunction, PHP simply doesn't support integer numbers over 2^31 - 1 and will convert them to a float. And yes, you should use the bc* functions for this. Copyright © 2001-2020 The PHP Group All rights reserved. Last updated: Mon Nov 30 15:01:27 2020 UTC