Factorials and PHP

April 19, 2007

When 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";
Posted by raditha at April 19, 2007 8:17 AM
Your Ad Here

 

Jabber  |  Linux  |  mySQL  |  PHP  |  Java  |  Site Map  |  Wiki

Downloads  |  About  |  Links  |  Contact  |  Home

 

Copyright © Raditha Dissanayake 2003 - 2007

Terms of Use  |  Privacy

 

 

April 2007
Sun Mon Tue Wed Thu Fri Sat
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30