Factorials and PHPApril 19, 2007When it comes to factorials Mysql struggles. Really struggles. Nothing is impossible but it certainly isn't easy to calculate values larger than 50! with mysql. So how does it's good friend PHP fare? Amazingly well. Using the arbitary precision math (BCMath) functions of PHP you can calculate factorials at the drop of a hat. It's blistering speed is a pleasent suprise. Using the arbitary precision math library. You can solve problem 20 at projec Euler in the blink of an eye. Here is the code.
$last = 1;
for($i=1 ; $i < 201 ; $i++)
{
$last = bcmul($last, $i);
echo "$i != $last\n";
}
$str=$last;
for($i=0; $i < strlen($str) ; $i++)
{
$sum = $sum +substr($str,$i,1);
}
echo "\n$str\n";
echo "$sum";
|
|



