Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with large numbers in PHP

Tags:

php

bignum

To use modular exponentiation as you would require when using the Fermat Primality Test with large numbers (100,000+), it calls for some very large calculations.

When I multiply two large numbers (eg: 62574 and 62574) PHP seems to cast the result to a float. Getting the modulus value of that returns strange values.

$x = 62574 * 62574;
var_dump($x);          // float(3915505476) ... correct
var_dump($x % 104659); // int(-72945)  ... wtf.

Is there any way to make PHP perform these calculations properly? Alternatively, is there another method for finding modulus values that would work for large numbers?

like image 937
nickf Avatar asked Oct 17 '08 07:10

nickf


3 Answers

For some reason, there are two standard libraries in PHP handling the arbitrary length/precision numbers: BC Math and GMP. I personally prefer GMP, as it's fresher and has richer API.

Based on GMP I've implemented Decimal2 class for storing and processing currency amounts (like USD 100.25). A lot of mod calculations there w/o any problems. Tested with very large numbers.

like image 61
Ivan Krechetov Avatar answered Nov 12 '22 12:11

Ivan Krechetov


use this

 $num1 = "123456789012345678901234567890";
 $num2 = "9876543210";
 $r    = mysql_query("Select @sum:=$num1 + $num2");
 $sumR = mysql_fetch_row($r);
 $sum  = $sumR[0];
like image 43
K.Sya Avatar answered Nov 12 '22 13:11

K.Sya


have you taken a look at bcmod()? php has issues with integers over 2^31 - 1 on 32 bit platforms.

var_dump(bcmod("$x", '104659') ); // string(4) "2968"
like image 21
Owen Avatar answered Nov 12 '22 13:11

Owen