|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #52906 gmp_mod returns negative result when non-negative is expected
Submitted: 2010-09-22 11:48 UTC Modified: 2010-10-01 02:13 UTC
From: kkcagg at gmail dot com Assigned: stas (profile)
Status: Closed Package: GNU MP related
PHP Version: 5.3.3 OS: Linux
Private report: No CVE-ID: None
 [2010-09-22 11:48 UTC] kkcagg at gmail dot com
GMP version	4.2.2

Running the function in test script returns the output of -5 when 5 is expected.
Documentation ( asserts that the 
result is always non-negative. This is not the case in actuality. Bug type could 
be either a bug or documentation problem.

Test script:
echo gmp_intval(gmp_mod(-2,7));

Expected result:

Actual result:


gmp_mod (last revision 2010-09-22 15:43 UTC by

Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2010-09-22 17:21 UTC]
-Status: Open +Status: Analyzed
 [2010-09-22 17:21 UTC]
This is a bug in the PHP extension. Worse, the result differs if you pass a GMP resource instead of an integer:

$ php -r "echo gmp_intval(gmp_mod(-2, gmp_add(6,1)));"

The problem is that gmp_zval_binary_ui_op_ex changes the sign of the result if it uses the unsigned integer variant of the GMP API and the first operand is negative. This may be the correct for other binary functions (I haven't checked), but it isn't for mod.

The documentation mirrors the upstream documentation, which says:

— Function: void mpz_mod (mpz_t r, mpz_t n, mpz_t d)
— Function: unsigned long int mpz_mod_ui (mpz_t r, mpz_t n, unsigned long int d)

Set r to n mod d. The sign of the divisor is ignored; the result is always non-negative.
 [2010-09-22 17:43 UTC]
The following patch has been added/updated:

Patch Name: gmp_mod
Revision:   1285170233
 [2010-09-22 17:44 UTC]
-Status: Analyzed +Status: Verified -Assigned To: +Assigned To: stas
 [2010-10-01 02:12 UTC]
Automatic comment from SVN on behalf of stas
Log: Fix bug #52906	gmp_mod returns negative result when non-negative is expected
 [2010-10-01 02:13 UTC]
-Status: Verified +Status: Closed
 [2010-10-01 02:13 UTC]
This bug has been fixed in SVN.

Snapshots of the sources are packaged every three hours; this change
will be in the next snapshot. You can grab the snapshot at
Thank you for the report, and for helping us make PHP better.

fixed, thanks
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sun Jun 16 18:01:30 2024 UTC