If you've got a number that is too big you can divide the problem into several steps with smaller numbers. An example:
Suppose we do this in steps of 3 digits. So, 1550 % 16
is the same as first doing 155 % 16
, which is 11
. After this first step we combine the result with what was left of the whole number. That is: 11
and 0
which gives 110
. We are now left with only 3 digits, so we do 110 % 16
which is 14
. So the result is 14
.
We can implement this in a function, I use 8 digits at once, because it is quicker:
function modulo($value, $modulo)
{
while ((strlen($value) > strlen($modulo)) ||
(intval($value) >= $modulo)) {
$head = substr($value, 0, 8);
$tail = substr($value, 8);
$value = ($head % $modulo) . $tail;
}
return $value;
}
Now if we do:
$value = "123456789101112131415171";
$modulo = 97;
echo modulo($value, $modulo);
We get 96
. Note how the big integer is a string, otherwise it won't work. There are a lot of implicit type conversions going on in this function.
See: PHP Sandbox.
A shorter version is possible, but is functionally the same:
function modulo($value, $modulo)
{
while ((strlen($value) > strlen($modulo)) ||
(intval($value) >= $modulo)) {
$value = (substr($value, 0, 8) % $modulo) . substr($value, 8);
}
return $value;
}
See: PHP Sandbox.