php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #25328 modulus operator problem with large numbers
Submitted: 2003-08-30 18:39 UTC Modified: 2003-08-31 03:00 UTC
From: hakon at haugnes dot name Assigned:
Status: Not a bug Package: *Math Functions
PHP Version: 4.3.2 OS: Redhat 8.0
Private report: No CVE-ID: 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:
--------------
However, this is produced: ([THE ERROR] added for your convenience)

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


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2003-08-30 19:06 UTC] hakon at haugnes dot name
I just realized that the [mal]functioning of % for large numbers is probably why the function BCMOD has been created...
 [2003-08-31 03:00 UTC] derick@php.net
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.

Derick
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Oct 31 23:01:28 2024 UTC