Comparing Big Numbers in PHP
Problem
What if I need to compare really big numbers in PHP? Like comparing 2^66 > 3^53?
Overview
This will work:
print (int) (pow(2,66) > pow(3,53));
PHP will convert the integers to scientific notation. But this script illustrates the limitation of normal operational syntax (i.e.: pow(2,66) > pow(3,53) vs. bccomp(bcpow(2,66), bcpow(3,53),1) > 0):
$max = 1000;
foreach ( range(1,$max) as $x )
{
if (
! ( pow(2,$x)+1 > pow(2,$x) ) ||
! ( pow(2,$x)-1 < pow(2,$x) ) ||
! ( pow(2,$x-1)*2 == pow(2,$x) )
) break;
}
$maxpow = $x-1;
$maxint = bcpow(2, $maxpow);
$Result['op'] = "max supported int: 2^$maxpow or $maxint\n";
foreach ( range(1,$max) as $x )
{
if (
! ( bccomp(bcadd(bcpow(2,$x),1), bcpow(2,$x)) == 1 ) ||
! ( bccomp(bcsub(bcpow(2,$x),1), bcpow(2,$x)) == -1 ) ||
! ( bccomp(bcmul(bcpow(2,$x-1),2), bcpow(2,$x)) == 0 )
) break;
}
$maxpow = $x-1;
$maxint = bcpow(2, $maxpow);
$Result['bc'] = "max supported int >= 2^$maxpow or $maxint\n";
printf("<pre>%s</pre>", print_r($Result,1));
Solution
Use bccomp. The script above can be found on the klenwell code site:
http://code.google.com/p/klenwell/source/browse/trunk/pastebin/bc_demo.php
Results will vary depending on the processing capacity of the system. Here’s the results on my machine:
(
[op] => max supported int: 2^52 or 4503599627370496
[bc] => max supported int >= 2^999 or 5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688
)