A little problem with array checksums using PHP

Back to Problem Solutions forum

Michal Gawel     2016-12-09 22:55:43

I was recently working at Array Checksums problem with PHP and I'm really desperated to do this.

I've checked topic about checksums in codeabbey wiki still nothing.

Here's the code:

<?php
$str = "1683 744645104 4323217 5987 15058 4854656 2 518452182 494 37869284 145 8166 75204 817 931 683178918 9 8620 771 81279 227701598";
$a = explode(" ", $str);
$limit = 10000007;
$r = 0;
for ($i = 0; $i < count($a); $i++) {
$r = (($r + $a[$i]) * 113); 
if ($r > $limit) {
    $r = $r % $limit;
}
}
echo $r;
?>

This script returns value of "-3.1509750703419E+33".

Example (3 1 4 1 5 9) runs fine and returns correct value.

Any ideas, please?

Eugene Lim     2016-12-10 07:04:54

Hi Micha,

This happens because there is an integer overflow when you multiply by 113.

Note that each element in the array can be up to 1,000,000. You would want to modulo it before performing the multiplication.

Hope it helps!

Michal Gawel     2016-12-10 08:51:00

Thanks Eugene, finally it works. I'm confused now, because I've tried it before posting and it didn't work.

Maybe I was just too tired and made some stupid mistakes.

Please login and solve 5 problems to be able to post at forum