I am facing troubles while doing mathematical operations in PHP specifically with big int
For example echo 600851475143 % 3;
prints 0 but 600851475143 is not divisible by 3
and
the factorial of 100 is
933262154439441526816992388562667004907159682643816214685929638952175999932299156089414639761565182862536979208272237582511852109168640000000000000000000000
but when I tried to calculate the factorial of 100 through the following code
$n = 100;
$product = 1;
for($i = 1 ; $i <= $n ; $i++){
$product = $product*$i;
}
$product = sprintf('%f', $product);
the result was
93326215443944102188325606108575267240944254854960571509166910400407995064242937148632694030450512898042989296944474898258737204311236641477561877016501813248.000000
I am not sure where I am wrong or it have to do something with the size of variable
See http://floating-point-gui.de/ for some explanation about this error.
bcmul uses strings to represent the data and will do exact calculations:
$n = 100;
$product = 1;
for($i = 1 ; $i <= $n ; $i++){
$product = bcmul($product,$i);
}
print $product;