Sunday, April 3, 2011

Factorial and Fibonacci in Phalanger



Update 1: using BigInteger Multiply method instead of unsupported custom * Operator.
Update 2: Porting code examples to Phalanger 3 - syntax changes on namespace use.

Here below a little program in Phalanger that implements 2 classes (in fact, they are 3). There is the main class, called Fiborial (Fibo(nnacci)+(Facto)rial) that implements the Fibonacci and the Factorial algorithms in two ways, one Recursive (using recursion) and the other Imperative (using loops and states). The second class is just an instance class that does the same thing, but its there just to show the difference between static and instance classes, and finally the third one (which will not appear in other languages) is the Program class which has the static execution method "Main".

You can also find 3 more little examples at the bottom. One prints out the Factorial's Series and Fibonacci's Series, the second one just shows a class that mixes both: static and instance members, and finally the third one that uses different return types (including System.Numerics.BigInteger) for the Factorial method to compare the timing and result.

As with the previous posts, you can copy and paste the code below in your favorite IDE/Editor and start playing and learning with it. This little "working" program will teach you some more basics of the Programming Language.

There are some "comments" on the code added just to tell you what are or how are some features called. In case you want to review the theory, you can read my previous post, where I give a definition of each of the concepts mentioned on the code. You can find it here: http://carlosqt.blogspot.com/2011/01/new-series-factorial-and-fibonacci.html 


The Fiborial Program

<?php      
# Factorial and Fibonacci in Phalanger        
namespace FiborialPhp;

use System;
use System\Collections\Generic as G;
use System\Diagnostics as D;
use System\Numerics as N;

# Instance Class           
# static is not a class modifier in PHP    
[\Export]
class StaticFiborial    
{      
    # Static Field     
    private static $className;    
    # no available static __constructor support    
    # Static Initializer Method instead, but need to be explicitly invoked    
    public static function StaticFiborialConstructor()    
    {                
        $className = "Static Constructor";    
        echo $className . "\n";    
    }            
    # Static Method - Factorial Recursive    
    public static function FactorialR(int $n)    
    {      
        if($n == 1)     
            return N\BigInteger::$One;  
        else                    
            return N\BigInteger::Multiply(new N\BigInteger($n), self::FactorialR($n-1));  
    }            
    # Static Method - Factorial Imperative        
    public static function FactorialI(int $n)     
    {                    
        $res = N\BigInteger::$One;
        for ($i = $n; $i >= 1; $i--)  
            $res = N\BigInteger::Multiply($res, new N\BigInteger($i));                  
        return $res;    
    }       
    # Static Method - Fibonacci Recursive        
    public static function FibonacciR(int $n)     
    {        
        if ($n < 2)    
            return 1;        
        else        
            return self::FibonacciR($n - 1) + self::FibonacciR($n - 2);        
    }    
    # Static Method - Fibonacci Imperative        
    public static function FibonacciI(int $n)     
    {    
        $pre = 0; $cur = 0; $tmp = 0;    
        $pre = 1; $cur = 1;    
        for ($i = 2; $i <= $n; $i++)     
        {    
            $tmp = $cur + $pre;        
            $pre = $cur;        
            $cur = $tmp;        
        }        
        return $cur;    
    }    
    # Static Method - Benchmarking Algorithms        
    public static function BenchmarkAlgorithm(int $algorithm, G\List<:int:> $values)     
    {    
        $timer = new D\Stopwatch();    
        $i = 0;     
        $testValue = 0;                
        $facTimeResult = N\BigInteger::$Zero;  
        $fibTimeResult = 0;        
                
        # "Switch" Flow Constrol Statement        
        switch ($algorithm)        
        {        
            case 1:        
                echo "\nFactorial Imperative:\n";    
                # "For" Loop Statement        
                for ($i = 0; $i < $values->Count; $i++)      
                {                                                    
                    $testValue = $values->get_Item($i);    
                    # Taking Time        
                    $timer->Start();        
                    $facTimeResult = self::FactorialI($testValue);        
                    $timer->Stop();                                
                    # Getting Time                              
                    echo " ($testValue) = {$timer->Elapsed->ToString()}\n";    
                }                            
                break;        
            case 2:        
                echo "\nFactorial Recursive:\n";    
                # "While" Loop Statement        
                while ($i < $values->Count)        
                {                                
                    $testValue = $values->get_Item($i);                            
                    # Taking Time        
                    $timer->Start();        
                    $facTimeResult = self::FactorialR($testValue);        
                    $timer->Stop();        
                    # Getting Time        
                    echo " ($testValue) = {$timer->Elapsed->ToString()}\n";    
                    $i++;    
                }    
                break;        
            case 3:        
                echo "\nFibonacci Imperative:\n";    
                # "Do-While" Loop Statement        
                do     
                {        
                    $testValue = $values->get_Item($i);    
                    # Taking Time        
                    $timer->Start();        
                    $fibTimeResult = self::FibonacciI($testValue);        
                    $timer->Stop();        
                    # Getting Time        
                    echo " ($testValue) = {$timer->Elapsed->ToString()}\n";    
                    $i++;        
                } while ($i < $values->Count);                            
                break;        
            case 4:        
                echo "\nFibonacci Recursive:\n";    
                # "ForEach" Loop Statement        
                foreach ($values as $item)        
                {        
                    $testValue = (int)$item;        
                    # Taking Time        
                    $timer->Start();        
                    $fibTimeResult = self::FibonacciR($testValue);    
                    $timer->Stop();        
                    # Getting Time        
                    echo " ($testValue) = {$timer->Elapsed->ToString()}\n";    
                }        
                break;        
            default:        
                echo "DONG!\n";    
                break;    
        }                        
    }        
}    
    
[\Export]     
# Instance Class    
class InstanceFiborial    
{      
    # Instance  Field     
    private $className;    
    # Instance Constructor                            
    function __construct()      
    {      
        $this->className = "Instance Constructor";    
        echo $this->className . "\n";    
    }    
    # Instance Method - Factorial Recursive    
    public function FactorialR(int $n)    
    {      
        # Calling Static Method    
        return StaticFiborial::FactorialR($n);    
    }    
    # Instance Method - Factorial Imperative        
    public function FactorialI(int $n)     
    {        
        # Calling Static Method    
        return StaticFiborial::FactorialI($n);    
    }       
    # Instance Method - Fibonacci Recursive        
    public function FibonacciR(int $n)     
    {        
        # Calling Static Method    
        return StaticFiborial::FibonacciR($n);    
    }    
    # Instance Method - Fibonacci Imperative        
    public function FibonacciI(int $n)     
    {    
        # Calling Static Method    
        return StaticFiborial::FibonacciI($n);    
    }    
}    
    
# Console Program      
class Program      
{      
    public static function Main()      
    {      
        # Static Initializer/Constructor for StaticFiborial Class     
        # explicitly called somewhere in your code ^_^    
        StaticFiborial::StaticFiborialConstructor();    
                
        echo "\nStatic Class\n";    
        # Calling Static Class and Methods      
        # No instantiation needed. Calling method directly from the class      
        echo "FacImp(5) = " . StaticFiborial::FactorialI(5)->ToString() . "\n";    
        echo "FacRec(5) = " . StaticFiborial::FactorialR(5)->ToString() . "\n";    
        echo "FibImp(11)= " . StaticFiborial::FibonacciI(11)->ToString() . "\n";    
        echo "FibRec(11)= " . StaticFiborial::FibonacciR(11)->ToString() . "\n";    
      
        echo "\nInstance Class\n";      
        # Calling Instance Class and Methods      
        # Need to instantiate before using. Calling method from instantiated object      
        $ff = new InstanceFiborial();    
        echo "FacImp(5) = {$ff->FactorialI(5)->ToString()}\n";    
        echo "FacRec(5) = {$ff->FactorialR(5)->ToString()}\n";    
        echo "FibImp(11)= {$ff->FibonacciI(11)->ToString()}\n";    
        echo "FibRec(11)= {$ff->FibonacciR(11)->ToString()}\n";    
                              
        # From 5 to 50 by 5    
        $values = new G\List<:int:>;    
        for($i = 5; $i <= 50; $i += 5)    
            $values->Add($i);    
    
        # Benchmarking Fibonacci      
        # 1 = Factorial Imperative      
        StaticFiborial::BenchmarkAlgorithm(1, $values);    
        # 2 = Factorial Recursive      
        StaticFiborial::BenchmarkAlgorithm(2, $values);    
        # Benchmarking Factorial      
        # 3 = Fibonacci Imperative      
        StaticFiborial::BenchmarkAlgorithm(3, $values);    
        # 4 = Fibonacci Recursive      
        StaticFiborial::BenchmarkAlgorithm(4, $values);    
    
        # Stop and exit      
        echo "Press any key to exit...";      
        fgets(STDIN);
        return 0;      
    }      
}    
 
?>

And the Output is:




































Printing the Factorial and Fibonacci Series
<?php        
namespace FiborialSeries;
use System;
use System\Text as T;    
use System\Numerics as N;
      
[\Export]
class Fiborial    
{      
    # Using a StringBuilder as a list of string elements                
    static function GetFactorialSeries(int $n)     
    {            
        # Create the String that will hold the list        
        $series = new T\StringBuilder();        
        # We begin by concatenating the number you want to calculate        
        # in the following format: "!# ="        
        $series->Append("!");        
        $series->Append($n);        
        $series->Append(" = ");        
        # We iterate backwards through the elements of the series        
        for ($i = $n; $i <= $n && $i > 0; $i--)     
        {        
            # and append it to the list        
            $series->Append($i);    
            if ($i > 1)        
                $series->Append(" * ");        
            else         
                $series->Append(" = ");         
        }        
        # Get the result from the Factorial Method        
        # and append it to the end of the list                                        
        # $series->Append(self::Factorial($n)->ToString());    
        # BUT! that throws an exception with big numbers (> fact(30))    
        # Overflow ex "Value was either too large or too small for a Decimal."  
        # because I think it is a bug i used an ugly workaround which is  
        # using the "." in the return.  
        return $series->ToString() . self::Factorial($n)->ToString();  
    }        
        
    # Using a StringBuilder as a list of string elements        
    static function GetFibonnaciSeries(int $n)        
    {        
        # Create the String that will hold the list        
        $series = new T\StringBuilder();    
        # We begin by concatenating the first 3 values which        
        # are always constant        
        $series->Append("0, 1, 1");        
        # Then we calculate the Fibonacci of each element        
        # and add append it to the list        
        for ($i = 2; $i <= $n; $i++)        
        {        
            if ($i < $n)        
                $series->Append(", ");        
            else        
                $series->Append(" = ");        
            
            $series->Append(self::Fibonacci($i));    
        }        
        # return the list as a string        
        return $series->ToString();        
    }        
    
    static function Factorial(int $n)    
    {      
        if($n == 1)     
            return new N\BigInteger(1);  
        else                    
            return N\BigInteger::Multiply(new N\BigInteger($n), self::Factorial($n - 1));  
    }    
            
    static function Fibonacci(int $n)     
    {        
        if ($n < 2)    
            return 1;    
        else        
            return self::Fibonacci($n - 1) + self::Fibonacci($n - 2);        
    }        
}    
    
class Program      
{      
    public static function Main()      
    {      
        # Printing Factorial Series        
        echo "\n";    
        echo Fiborial::GetFactorialSeries(5) . "\n";    
        echo Fiborial::GetFactorialSeries(7) . "\n";    
        echo Fiborial::GetFactorialSeries(9) . "\n";    
        echo Fiborial::GetFactorialSeries(11) . "\n";    
        echo Fiborial::GetFactorialSeries(40) . "\n";      
        # Printing Fibonacci Series  
        echo "\n";    
        echo Fiborial::GetFibonnaciSeries(5) . "\n";    
        echo Fiborial::GetFibonnaciSeries(7) . "\n";    
        echo Fiborial::GetFibonnaciSeries(9) . "\n";    
        echo Fiborial::GetFibonnaciSeries(11) . "\n";    
        echo Fiborial::GetFibonnaciSeries(40) . "\n";    
                 
        fgets(STDIN);
        return 0;      
    }      
}    
?>

And the Output is:

















Mixing Instance and Static Members in the same Class

Instance classes can contain both, instance and static members such as: fields, properties, constructors, methods, etc.

<?php    
namespace FiborialExtras2;
use System;

# Instance Class  
[\Export]       
class Fiborial  
{    
    # Instance Field  
    private $instanceCount;  
    # Static Field  
    private static $staticCount;          
    # Instance Read-Only Property/Getter  
    # Within instance members, you can always use    
    # the "this" reference pointer to access your (instance) members.  
    public function getInstanceCount()  
    {  
        return $this->instanceCount;  
    }  
    # Static Read-Only Property/Getter  
    # As with Static Methods, you cannot reference your class members  
    # with the "this" reference pointer since static members are not  
    # instantiated.          
    public static function getStaticCount()  
    {  
        return $staticCount;  
    }  
    # Instance Constructor            
    public function __construct()    
    {    
        $this->instanceCount = 0;  
        echo "\nInstance Constructor {$this->instanceCount}\n";  
    }    
    # Static Constructor  
    public static function FiborialStaticConstructor()  
    {  
        $staticCount = 0;  
        echo "\nStatic Constructor {$staticCount}\n";  
    }      
    # Instance Method  
    public function Factorial(int $n)  
    {    
        $this->instanceCount += 1;  
        echo "\nFactorial({$n})\n";  
    }  
    # Static Method  
    public static function Fibonacci(int $n)   
    {      
        $staticCount += 1;  
        echo "\nFibonacci({$n})\n";  
    }      
}  
  
class Program    
{    
    public static function Main()    
    {    
        # Calling Static Constructor/Initializer and Methods  
        # No need to instantiate  
        Fiborial::FiborialStaticConstructor();  
        Fiborial::Fibonacci(5);              
  
        // Calling Instance Constructor and Methods  
        // Instance required  
        $fib = new Fiborial();  
        $fib->Factorial(5);  
  
        Fiborial::Fibonacci(15);              
        $fib->Factorial(5);  
  
        // Calling Instance Constructor and Methods  
        // for a second object  
        $fib2 = new Fiborial();  
        $fib2->Factorial(5);  
              
        echo "\n";  
        // Calling Static Property  
        echo "Static Count = " . Fiborial::getStaticCount() . "\n";  
        // Calling Instance Property of object 1 and 2  
        echo "Instance 1 Count = {$fib->getInstanceCount()}\n";  
        echo "Instance 2 Count = {$fib2->getInstanceCount()}\n";  
  
        fgets(STDIN);    
        return 0;    
    }    
}  
?>

And the Output is:























Factorial using System.Int64, System.Double, System.Numerics.BigInteger

The Factorial of numbers over 20 are massive!
For instance: !40 = 815915283247897734345611269596115894272000000000!
Because of this, the previous version of this program was giving the "wrong" result
!40 = -70609262346240000 when using "long" (System.Int64) type, but it was not until I did the Fiborial version in VB.NET that I realized about this faulty code, because instead of giving me a wrong value, VB.NET, JScript.NET, Boo execution thrown an Overflow Exception when using the "Long/long" (System.Int64) type.

My first idea was to use ulong and ULong, but both failed for "big" numbers. I then used Double (double floating point) type and got no more exception/wrong result. The result of the factorial was now correct !40 = 1.1962222086548E+56, but still I wanted to show the Integer value of it, so I did some research and found that there is a new System.Numerics.BigInteger class in the .NET Framework 4.0. Adding the reference to the project and using this new class as the return type of the Factorial methods, I was able to get the result I was expecting.
!40 = 815915283247897734345611269596115894272000000000

What I also found was that using different types change the time the algorithm takes to finish:
System.Int64 < System.Double < System.Numerics.BigInteger
Almost by double!

To illustrate what I just "tried" to say, lets have a look at the following code and the output we get.

<?php      
use System\Numerics as N;
use System\Diagnostics as D;      
    
function FactorialInt64(int $n)     
{        
    if ($n == 1)        
        return 1;        
    else        
        return $n * FactorialInt64($n - 1);        
}        
    
function FactorialDouble(int $n)     
{        
    if ($n == 1)        
        return (double)1;        
    else        
        return (double)($n * FactorialDouble($n - 1));    
}    
    
function FactorialBigInteger(int $n)     
{        
    if($n == 1)     
        return N\BigInteger::$One;  
    else                    
        return N\BigInteger::Multiply(new N\BigInteger($n), FactorialBigInteger($n - 1));  
}    
    
class Program    
{    
    public static function Main()      
    {      
            $timer = new D\Stopwatch();    
            $facIntResult = 0;        
            $facDblResult = (double)0;        
            $facBigResult = N\BigInteger::$Zero;     
    
            echo "\nFactorial using Int64\n";        
            // Benchmark Factorial using Int64        
            for ($i = 5; $i <= 50; $i += 5)        
            {        
                $timer->Start();        
                $facIntResult = FactorialInt64($i);        
                $timer->Stop();        
                echo " ({$i}) = {$timer->Elapsed->ToString()} : {$facIntResult}\n";    
            }                    
            echo "\nFactorial using Double\n";        
            // Benchmark Factorial using Double    
            for ($i = 5; $i <= 50; $i += 5)        
            {        
                $timer->Start();        
                $facDblResult = FactorialDouble($i);        
                $timer->Stop();        
                echo " ({$i}) = {$timer->Elapsed->ToString()} : {$facDblResult}\n";    
            }        
            echo "\nFactorial using N\BigInteger\n";    
            // Benchmark Factorial using N\BigInteger                    
            for ($i = 5; $i <= 50; $i += 5)    
            {        
                    
                $timer->Start();        
                $facBigResult = FactorialBigInteger($i);        
                $timer->Stop();        
                echo " ({$i}) = {$timer->Elapsed->ToString()} : {$facBigResult->ToString()}\n";    
            }      
                          
            fgets(STDIN);      
            return 0;      
    }      
}    
?>

NOTE: you need to manually add a reference to the System.Numerics.dll assembly to your project so you can add it to your code.

And the Output is:

 

No comments:

Post a Comment