Skip to content
Advertisement

How can I calculate a really long number with modulo without using bcmod?

The bcmod function is deactivated and I won’t be able to activate this because its not my own server.

For a reason I need to calculate an integer with a length of atleast 24 with modulo 97. Integer cant be that long, thats why it can’t work…

I already tried it with simple operator “%” and the “fcmod” lib but this returns me completely wrong numbers.

Does someone know if I can solve this by my own without any other libraries or do I really need “bcmod”?

This would be the code as example:

123456789101112131415171%97 The real answer would be 96 but it returns me -94

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement