Sunday, April 3, 2011

Factorial and Fibonacci in Phalanger



Updated: using BigInteger Multiply method instead of unsupported custom * Operator.

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    
import namespace System;    
import namespace System:::Collections:::Generic;  
import namespace System:::Diagnostics;  
import namespace System:::Numerics;  
  
namespace FiborialPhp   
{    
    [Export]   
    # Instance Class         
    # static is not a class modifier in PHP  
    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 new BigInteger(1);
            else                  
                return BigInteger::Multiply(new BigInteger($n), self::FactorialR($n-1));
        }          
        # Static Method - Factorial Imperative      
        public static function FactorialI(int $n)   
        {                  
            $res = new BigInteger(1);            
            for ($i = $n; $i >= 1; $i--)
                $res = BigInteger::Multiply($res, new 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, i'List'<:int:> $values)   
        {  
            $timer = new Stopwatch();  
            $i = 0;   
            $testValue = 0;              
            $facTimeResult = new BigInteger(0);
            $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 FiborialPhp:::StaticFiborial::FactorialR($n);  
        }  
        # Instance Method - Factorial Imperative      
        public function FactorialI(int $n)   
        {      
            # Calling Static Method  
            return FiborialPhp:::StaticFiborial::FactorialI($n);  
        }     
        # Instance Method - Fibonacci Recursive      
        public function FibonacciR(int $n)   
        {      
            # Calling Static Method  
            return FiborialPhp:::StaticFiborial::FibonacciR($n);  
        }  
        # Instance Method - Fibonacci Imperative      
        public function FibonacciI(int $n)   
        {  
            # Calling Static Method  
            return FiborialPhp:::StaticFiborial::FibonacciI($n);  
        }  
    }  
  
    # Console Program    
    class Program    
    {    
        public static function Main()    
        {    
            # Static Initializer/Constructor for StaticFiborial Class   
            # explicitly called somewhere in your code ^_^  
            FiborialPhp:::StaticFiborial::StaticFiborialConstructor();  
              
            echo "\nStatic Class\n";  
            # Calling Static Class and Methods    
            # No instantiation needed. Calling method directly from the class    
            echo "FacImp(5) = " . FiborialPhp:::StaticFiborial::FactorialI(5)->ToString() . "\n";  
            echo "FacRec(5) = " . FiborialPhp:::StaticFiborial::FactorialR(5)->ToString() . "\n";  
            echo "FibImp(11)= " . FiborialPhp:::StaticFiborial::FibonacciI(11)->ToString() . "\n";  
            echo "FibRec(11)= " . FiborialPhp:::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 FiborialPhp:::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";  
    
            # PHP/CLR provides syntax of quoted identifiers.   
            # the List class can be referred to by i'List' quoted identifier.  
            # to avoid ambiguity with PHP List keyword  
            # From 5 to 50 by 5  
            $values = new i'List'<:int:>;  
            for($i = 5; $i <= 50; $i += 5)  
                $values->Add($i);  
  
            # Benchmarking Fibonacci    
            # 1 = Factorial Imperative    
            FiborialPhp:::StaticFiborial::BenchmarkAlgorithm(1, $values);  
            # 2 = Factorial Recursive    
            FiborialPhp:::StaticFiborial::BenchmarkAlgorithm(2, $values);  
            # Benchmarking Factorial    
            # 3 = Fibonacci Imperative    
            FiborialPhp:::StaticFiborial::BenchmarkAlgorithm(3, $values);  
            # 4 = Fibonacci Recursive    
            FiborialPhp:::StaticFiborial::BenchmarkAlgorithm(4, $values);  
  
            # Stop and exit    
            echo "Press any key to exit...";    
            fgets(STDIN);    
            return 0;    
        }    
    }  
}  
?>

And the Output is:

































Humm, looks like Fibonnaci's algorithm implemented using recursion is definitively more complex than the others 3 right? I will grab these results for this and each of the upcoming posts to prepare a comparison of time execution between all the programming languages, then we will be able to talk about the algorithm's complexity as well.

Printing the Factorial and Fibonacci Series
<?php    
import namespace System;    
import namespace System:::Text;  
import namespace System:::Numerics;  
  
namespace FiborialSeries  
{    
    [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 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 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 BigInteger(1);
            else                  
                return BigInteger::Multiply(new 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 FiborialSeries:::Fiborial::GetFactorialSeries(5) . "\n";  
            echo FiborialSeries:::Fiborial::GetFactorialSeries(7) . "\n";  
            echo FiborialSeries:::Fiborial::GetFactorialSeries(9) . "\n";  
            echo FiborialSeries:::Fiborial::GetFactorialSeries(11) . "\n";  
            echo FiborialSeries:::Fiborial::GetFactorialSeries(40) . "\n";    
            # Printing Fibonacci Series
            echo "\n";  
            echo FiborialSeries:::Fiborial::GetFibonnaciSeries(5) . "\n";  
            echo FiborialSeries:::Fiborial::GetFibonnaciSeries(7) . "\n";  
            echo FiborialSeries:::Fiborial::GetFibonnaciSeries(9) . "\n";  
            echo FiborialSeries:::Fiborial::GetFibonnaciSeries(11) . "\n";  
            echo FiborialSeries:::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  
import namespace System;  

namespace FiborialExtras2
{  
    # 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
            FiborialExtras2:::Fiborial::FiborialStaticConstructor();
            FiborialExtras2:::Fiborial::Fibonacci(5);            

            // Calling Instance Constructor and Methods
            // Instance required
            $fib = new FiborialExtras2:::Fiborial();
            $fib->Factorial(5);

            FiborialExtras2:::Fiborial::Fibonacci(15);            
            $fib->Factorial(5);

            // Calling Instance Constructor and Methods
            // for a second object
            $fib2 = new FiborialExtras2:::Fiborial();
            $fib2->Factorial(5);
            
            echo "\n";
            // Calling Static Property
            echo "Static Count = " . FiborialExtras2:::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    
import namespace System;    
import namespace System:::Numerics;    
import namespace System:::Diagnostics;    
  
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 new BigInteger(1);
    else                  
        return BigInteger::Multiply(new BigInteger($n), FactorialBigInteger($n - 1));
}  
  
class Program  
{  
    public static function Main()    
    {    
            $timer = new Stopwatch();  
            $facIntResult = 0;      
            $facDblResult = (double)0;      
            $facBigResult = new BigInteger(0);   
  
            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 BigInteger\n";  
            // Benchmark Factorial using 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:

 

0 comments:

Post a Comment