Sunday, March 27, 2011

Factorial and Fibonacci in Nemerle



Here below a little program in Nemerle 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

// Factorial and Fibonacci in Nemerle
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using Nemerle.IO;

namespace FiborialN
{
    // Module = Static Class
    // all members become static by default
    // no need to explicitly use static on members (i did anyway)
    module StaticFiborial
    {
        // Static Field
        static mutable className : string; 
        // Static Constructor
        static this()
        {
            className = "Static Constructor";
            printf("%s", className);
        }
        // Static Method - Factorial Recursive
        public static FactorialR(n : int) : BigInteger
        {            
            if (n == 1)
                 BigInteger(1);
            else 
                 BigInteger(n) * FactorialR(n - 1);
        }
        // Static Method - Factorial Imperative
        public static FactorialI(n : int) : BigInteger
        {
            mutable res : BigInteger = BigInteger(1);
            for (mutable i : int = n; i >= 1; i--)
                res *= i;
            res;
        }
        // Static Method - Fibonacci Recursive
        public static FibonacciR(n : int) : long
        {
            def oneLong : long = 1;
            if (n < 2)
                oneLong;
            else
                FibonacciR(n - 1) + FibonacciR(n - 2);
        }
        // Static Method - Fibonacci Imperative
        public static FibonacciI(n : int) : long
        {            
            mutable pre : long = 1;
            mutable cur : long = 1;
            mutable tmp : long = 0;
            
            for (mutable i : int = 2; i <= n; i++)
            {
                tmp = cur + pre;
                pre = cur;
                cur = tmp;
            }
            cur;
        }
        // Static Method - Benchmarking Algorithms
        public static BenchmarkAlgorithm(algorithm : int, values : list[int]) : void
        {            
            def timer : Stopwatch = Stopwatch();
            mutable i : int = 0;
            mutable testValue : int = 0;
            mutable facTimeResult : BigInteger = BigInteger(0);
            mutable fibTimeResult : long = 0;
           
            // "Switch" Flow Constrol Statement
            match (algorithm)
            {
                | 1 =>
                    printf("\nFactorial Imperative:\n");
                    // "For" Loop Statement
                    for (i = 0; i < values.Length; i++)
                    {
                        testValue = values.Nth(i);
                        // Taking Time
                        timer.Start();
                        facTimeResult = FactorialI(testValue);
                        timer.Stop();                        
                        // Getting Time
                        printf(" (%d) = %s\n", testValue, timer.Elapsed.ToString());
                    }
                | 2 =>
                    printf("\nFactorial Recursive:\n");
                    // 'While' Loop Statement  
                    while (i < values.Length) 
                    {
                        testValue = values.Nth(i);  
                        // Taking Time  
                        timer.Start();  
                        facTimeResult = FactorialR(testValue);  
                        timer.Stop();  
                        // Getting Time  
                        printf(" (%d) = %s\n", testValue, timer.Elapsed.ToString());
                        i++;
                    }
                | 3 =>
                    printf("\nFibonacci Imperative:\n");
                    // 'Do-While' Loop Statement  
                    do {  
                        testValue = values.Nth(i);  
                        // Taking Time 
                        timer.Start();  
                        fibTimeResult = FibonacciI(testValue);  
                        timer.Stop();  
                        // Getting Time  
                        printf(" (%d) = %s\n", testValue, timer.Elapsed.ToString());
                        i++;  
                    } while (i < values.Length);  
                | 4 =>
                    printf("\nFibonacci Recursive:\n");
                    // 'For Each' Loop Statement  
                    foreach (item : int in values) {  
                        testValue = item;
                        // Taking Time  
                        timer.Start();  
                        fibTimeResult = FibonacciR(testValue);  
                        timer.Stop();  
                        // Getting Time  
                        printf(" (%d) = %s\n", testValue, timer.Elapsed.ToString());
                    }  
                | _ => printf("DONG!");
            }                
        }
    }
    
    // Instance Class  
    public class InstanceFiborial 
    {  
        // Instance Field  
        mutable className : String;  
        // Instance Constructor  
        public this() 
        {  
            this.className = "Instance Constructor";  
            printf("%s", this.className);
        }  
        // Instance Method - Factorial Recursive  
        public FactorialR(n : int) : BigInteger 
        {  
            // Calling Static Method  
            StaticFiborial.FactorialR(n);  
        }  
        // Instance Method - Factorial Imperative  
        public FactorialI(n : int) : BigInteger 
        {  
            // Calling Static Method  
            StaticFiborial.FactorialI(n);  
        }  
        // Instance Method - Fibonacci Recursive  
        public FibonacciR(n : int) : long 
        {  
            // Calling Static Method  
            StaticFiborial.FibonacciR(n);  
        }  
        // Instance Method - Factorial Imperative  
        public FibonacciI(n : int) : long 
        {  
            // Calling Static Method  
            StaticFiborial.FibonacciI(n);  
        }  
    }  
    
    module Program
    {
        Main() : void
        {          
            printf("\nStatic Class\n");
            // Calling Static Class and Methods  
            // No instantiation needed. Calling method directly from the class 
            printf("FacImp(5) = %s\n", StaticFiborial.FactorialI(5).ToString());  
            printf("FacRec(5) = %s\n", StaticFiborial.FactorialR(5).ToString());  
            printf("FibImp(11)= %s\n", StaticFiborial.FibonacciI(11).ToString());  
            printf("FibRec(11)= %s\n", StaticFiborial.FibonacciR(11).ToString());  

            printf("\nInstance Class\n");  
            // Calling Instance Class and Methods   
            // Need to instantiate before using. Calling method from instantiated object  
            def ff : InstanceFiborial = InstanceFiborial();  
            printf("FacImp(5) = %s\n", ff.FactorialI(5).ToString());  
            printf("FacRec(5) = %s\n", ff.FactorialR(5).ToString());  
            printf("FibImp(11)= %s\n", ff.FibonacciI(11).ToString());  
            printf("FibRec(11)= %s\n", ff.FibonacciR(11).ToString()); 

            // Create a (nemerle) list of integer values to test
            // From 5 to 50 by 5
            mutable values : list[int] = [];
            foreach (i in $[5,10..50])
                values ::= i;
                    
            // Benchmarking Fibonacci                       
            // 1 = Factorial Imperative              
            StaticFiborial.BenchmarkAlgorithm(1, values.Reverse());
            // 2 = Factorial Recursive  
            StaticFiborial.BenchmarkAlgorithm(2, values.Reverse());

            // Benchmarking Factorial              
            // 3 = Fibonacci Imperative  
            StaticFiborial.BenchmarkAlgorithm(3, values.Reverse());
            // 4 = Fibonacci Recursive  
            StaticFiborial.BenchmarkAlgorithm(4, values.Reverse());        

            // Stop and Exit 
            _ = Console.ReadLine();
        }
    }
}

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
using System;  
using System.Text;  
using System.Numerics;
using Nemerle.IO;

namespace FiborialSeries
{
    static class Fiborial
    {
        // Using a StringBuilder as a list of string elements  
        public static GetFactorialSeries(n : int) : string
        {  
            // Create the String that will hold the list  
            def series : StringBuilder = 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 (mutable i : int = 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(Factorial(n));  
            // return the list as a string  
            series.ToString();  
        }
        // Using a StringBuilder as a list of string elements  
        public static GetFibonnaciSeries(n : int) : string 
        {  
            // Create the String that will hold the list  
            def series : StringBuilder = 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 (mutable i : int = 2; i <= n; i++)  
            {  
                if (i < n)  
                    _ = series.Append(", ");  
                else  
                    _ = series.Append(" = ");  
                  
                _ = series.Append(Fibonacci(i));  
            }  
            // return the list as a string  
            series.ToString();  
        }  
        // Static Method - Factorial Recursive
        public static Factorial(n : int) : BigInteger
        {            
            if (n == 1)
                 BigInteger(1);
            else 
                 BigInteger(n) * Factorial(n - 1);
        }        
        // Static Method - Fibonacci Recursive
        public static Fibonacci(n : int) : long
        {
            def oneLong : long = 1;
            if (n < 2)
                oneLong;
            else
                Fibonacci(n - 1) + Fibonacci(n - 2);
        }        
    }
        
    module Program
    {
        Main() : void
        {          
            printf("\nStatic Class\n");
            // Printing Factorial Series  
            printf("\n");
            printf("%s\n", Fiborial.GetFactorialSeries(5));
            printf("%s\n", Fiborial.GetFactorialSeries(7));  
            printf("%s\n", Fiborial.GetFactorialSeries(9));  
            printf("%s\n", Fiborial.GetFactorialSeries(11));  
            printf("%s\n", Fiborial.GetFactorialSeries(40));  
            // Printing Fibonacci Series  
            printf("\n");
            printf("%s\n", Fiborial.GetFibonnaciSeries(5));  
            printf("%s\n", Fiborial.GetFibonnaciSeries(7));  
            printf("%s\n", Fiborial.GetFibonnaciSeries(9));  
            printf("%s\n", Fiborial.GetFibonnaciSeries(11));  
            printf("%s\n", Fiborial.GetFibonnaciSeries(40));              
        }
    }
}

And the Output is:



















Mixing Instance and Static Members in the same Class

We can also define instance classes that have both, instance and static members such as: fields, properties, constructors, methods, etc. However, we cannot do that if the class is marked as static because of the features mentioned in the previous post:
The main features of a static class are:
  • They only contain static members.
  • They cannot be instantiated.
  • They are sealed.
  • They cannot contain Instance Constructors

using System;  
namespace FiborialExtrasN2
{
    // Instance Class
    class Fiborial  
    {  
        // Instance Field  
        mutable instanceCount : int;  
        // Static Field  
        static mutable staticCount : int;          
        // Instance Read-Only Property  
        // Within instance members, you can always use    
        // the "this" reference pointer to access your (instance) members.  
        public InstanceCount : int
        {  
            get { this.instanceCount; }  
        }  
        // Static Read-Only Property  
        // Remeber that Properties are Methods to the CLR, so, you can also  
        // define static properties for static fields.   
        // As with Static Methods, you cannot reference your class members  
        // with the "this" reference pointer since static members are not  
        // instantiated.          
        public static StaticCount : int
        {  
            get { staticCount; }  
        }  
        // Instance Constructor  
        public this()  
        {  
            this.instanceCount = 0;  
            Console.WriteLine("\nInstance Constructor {0}", this.instanceCount);  
        }  
        // Static Constructor  
        static this()  
        {  
            staticCount = 0;  
            Console.WriteLine("\nStatic Constructor {0}", staticCount);  
        }  
  
        // Instance Method  
        public Factorial(n : int) : void
        {  
            this.instanceCount += 1;  
            Console.WriteLine("\nFactorial({0})", n);  
        }  
  
        // Static Method  
        public static Fibonacci(n : int) : void
        {  
            staticCount += 1;  
            Console.WriteLine("\nFibonacci({0})", n);  
        }                   
    }
        
    module Program
    {
        Main() : void
        {          
            // Calling Static Constructor and Methods  
            // No need to instantiate  
            Fiborial.Fibonacci(5);              
  
            // Calling Instance Constructor and Methods  
            // Instance required  
            def fib : Fiborial = Fiborial();  
            fib.Factorial(5);              
  
            Fiborial.Fibonacci(15);              
            fib.Factorial(5);  
  
            // Calling Instance Constructor and Methods  
            // for a second object  
            def fib2 : Fiborial = Fiborial();  
            fib2.Factorial(5);  
              
            Console.WriteLine();  
            // Calling Static Property  
            Console.WriteLine("Static Count = {0}", Fiborial.StaticCount);  
            // Calling Instance Property of object 1 and 2  
            Console.WriteLine("Instance 1 Count = {0}", fib.InstanceCount);  
            Console.WriteLine("Instance 2 Count = {0}", fib2.InstanceCount); 
        }
    }
}

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.

#pragma indent
using System;  
using System.Numerics;  
using System.Diagnostics;  
using System.Console;

namespace FiborialExtrasCs3

    module Program
        // Long Factorial
        public static FactorialInt64(n : int) : long
            def oneLong : long = 1;
            if (n == 1)
                 oneLong;
            else 
                 n * FactorialInt64(n - 1);

        // Double Factorial
        public static FactorialDouble(n : int) : double
            def oneDouble : double = 1;
            if (n == 1)
                oneDouble;
            else 
                 n * FactorialDouble(n - 1);

        // BigInteger Factorial
        public static FactorialBigInteger(n : int) : BigInteger
            if (n == 1)
                 BigInteger(1);
            else 
                 BigInteger(n) * FactorialBigInteger(n - 1);
    
        Main() : void
            def timer : Stopwatch = Stopwatch();  
            mutable facIntResult : long = 0;  
            mutable facDblResult : double = 0;  
            mutable facBigResult : BigInteger = BigInteger(0);
                        
            WriteLine("\nFactorial using Int64");
            // Benchmark Factorial using Int64
            // Overflow Exception!!!
            try
                foreach (i in $[5,10..50])
                    timer.Start();  
                    facIntResult = FactorialInt64(i);  
                    timer.Stop();
                    WriteLine(" ({0}) = {1} : {2}", i, timer.Elapsed, facIntResult);  
            catch
                | ex is OverflowException =>
                    // yummy ^_^  
                    WriteLine("Oops! {0}", ex.Message);
            
            WriteLine("\nFactorial using Double");  
            // Benchmark Factorial using Double  
            foreach (i in $[5,10..50])
                timer.Start();  
                facDblResult = FactorialDouble(i);
                timer.Stop();
                WriteLine(" ({0}) = {1} : {2}", i, timer.Elapsed, facDblResult);  
            
            WriteLine("\nFactorial using BigInteger");  
            // Benchmark Factorial using BigInteger
            foreach (i in $[5,10..50])
                timer.Start();
                facBigResult = FactorialBigInteger(i);
                timer.Stop();
                WriteLine(" ({0}) = {1} : {2}", i, timer.Elapsed, facBigResult);

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:

Tuesday, March 8, 2011

Factorial and Fibonacci in Boo



Here below a little program in Boo 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

// Factorial and Fibonacci in Boo
namespace FiborialBoo
import System
import System.Collections.Generic
import System.Diagnostics
import System.Numerics

// Static Class  
public static class StaticFiborial:
    // Static Field
    private className as string
    // Static Constructor
    def constructor():
        className = "Static Constructor"
        print className
    // Static Method - Factorial Recursive  
    public def FactorialR(n as int) as BigInteger:
        if n == 1:
            return 1  
        else:  
            return n * FactorialR(n - 1)
    // Static Method - Factorial Imperative  
    public def FactorialI(n as int) as BigInteger:
        res as BigInteger = 1
        for i as int in range(n, 1):
            res *= i
        return res
    // Static Method - Fibonacci Recursive  
    public def FibonacciR(n as int) as long:
        if n < 2:
            return 1  
        else:  
            return FibonacciR(n - 1) + FibonacciR(n - 2)
    // Static Method - Fibonacci Imperative
    public def FibonacciI(n as int) as long:
        pre as long = 1
        cur as long = 1
        tmp as long = 0
        for i as int in range(2, n+1):
            tmp = cur + pre
            pre = cur
            cur = tmp
        return cur
    // Static Method - Benchmarking Algorithms
    public def BenchmarkAlgorithm(algorithm as int, values as List[of int]) as void:
        timer as Stopwatch = Stopwatch()
        i as int = 0
        testValue as int = 0
        facTimeResult as BigInteger = 0
        fibTimeResult as long = 0  
        
        // "if-elif-else" Flow Control Statement  
        if algorithm == 1:
            print "\nFactorial Imperative:"
            // "For in range" Loop Statement 
            for i in range(values.Count):                
                testValue = values[i]
                // Taking Time  
                timer.Start()
                facTimeResult = FactorialI(testValue)
                timer.Stop()                          
                // Getting Time  
                print " (${testValue}) = ${timer.Elapsed}"
        elif algorithm == 2:
            print "\nFactorial Recursive:"
            // "While" Loop Statement
            while i < len(values):
                testValue = values[i]
                // Taking Time  
                timer.Start()
                facTimeResult = FactorialR(testValue)
                timer.Stop()                          
                // Getting Time  
                print " (${testValue}) = ${timer.Elapsed}"
                i += 1
        elif algorithm == 3:
            print "\nFibonacci Imperative:" 
            // "For in List" Loop Statement             
            for item as int in values:
                testValue = item
                // Taking Time
                timer.Start()
                fibTimeResult = FibonacciI(testValue)
                timer.Stop()
                // Getting Time
                print " (${testValue}) = ${timer.Elapsed}"                
        elif algorithm == 4:
            print "\nFibonacci Recursive:"
            // "For in List" Loop Statement 
            for item as int in values:
                testValue = item
                // Taking Time
                timer.Start()
                fibTimeResult = FibonacciR(testValue)
                timer.Stop()
                // Getting Time
                print " (${testValue}) = ${timer.Elapsed}"
        else:
            print "DONG!"

// Instance Class
public class InstanceFiborial:
    // Instances Field
    private className as string
    // Instance Constructor
    def constructor():
        self.className = "Instance Constructor"
        print self.className
    // Instance Method - Factorial Recursive
    public def FactorialR(n as int) as BigInteger:
        // Calling Static Method
        return StaticFiborial.FactorialR(n)
    // Instance Method - Factorial Imperative
    public def FactorialI(n as int) as BigInteger:
        // Calling Static Method
        return StaticFiborial.FactorialI(n)
    // Instance Method - Fibonacci Recursive  
    public def FibonacciR(n as int) as long:
        // Calling Static Method
        return StaticFiborial.FibonacciR(n)
    // Instance Method - Fibonacci Imperative
    public def FibonacciI(n as int) as long:
        // Calling Static Method
        return StaticFiborial.FibonacciI(n)

public def Main(argv as (string)):
    print "\nStatic Class"
    // Calling Static Class and Methods
    // No instantiation needed. Calling method directly from the class
    print "FacImp(5) = ${StaticFiborial.FactorialI(5)}"
    print "FacRec(5) = ${StaticFiborial.FactorialR(5)}"
    print "FibImp(11)= ${StaticFiborial.FibonacciI(11)}"
    print "FibRec(11)= ${StaticFiborial.FibonacciR(11)}"

    print "\nInstance Class"
    // Calling Instance Class and Methods
    // Need to instantiate before using. Calling method from instantiated object
    ff as InstanceFiborial = InstanceFiborial()
    print "FacImp(5) = ${ff.FactorialI(5)}"
    print "FacRec(5) = ${ff.FactorialR(5)}"
    print "FibImp(11)= ${ff.FibonacciI(11)}"
    print "FibRec(11)= ${ff.FibonacciR(11)}"

    // Create a (Boo) list of values to test  
    // From 5 to 50 by 5
    values as List[of int] = List[of int]()
    for i as int in range(5,55,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
    Console.ReadKey(true)

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
namespace FiborialSeries
import System
import System.Text
import System.Numerics

// Static Class  
public static class Fiborial:
    // Using a StringBuilder as a list of string elements  
    public def GetFactorialSeries(n as int) as string:  
        // Create the String that will hold the list  
        series as StringBuilder = 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 as int in range(n, 1):
            // 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(Factorial(n))
        // return the list as a string  
        return series.ToString()

    // Using a StringBuilder as a list of string elements  
    public def GetFibonnaciSeries(n as int) as string:
        // Create the String that will hold the list  
        series as StringBuilder = 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 as int in range(2, n+1):
            if i < n:
                series.Append(", ") 
            else:
                series.Append(" = ")  
            series.Append(Fibonacci(i))
        // return the list as a string  
        return series.ToString()
        
    public def Factorial(n as int) as BigInteger:
        if n == 1:
            return 1  
        else:  
            return n * Factorial(n - 1)    
    
    public def Fibonacci(n as int) as long:
        if n < 2:
            return 1  
        else:  
            return Fibonacci(n - 1) + Fibonacci(n - 2)

public def Main(argv as (string)):
    // Printing Factorial Series  
    print ""
    print Fiborial.GetFactorialSeries(5)
    print Fiborial.GetFactorialSeries(7)
    print Fiborial.GetFactorialSeries(9)
    print Fiborial.GetFactorialSeries(11)
    print Fiborial.GetFactorialSeries(40)
    // Printing Fibonacci Series  
    print ""
    print Fiborial.GetFibonnaciSeries(5)
    print Fiborial.GetFibonnaciSeries(7)
    print Fiborial.GetFibonnaciSeries(9)
    print Fiborial.GetFibonnaciSeries(11)
    print Fiborial.GetFibonnaciSeries(40)
    
    Console.ReadKey(true)

And the Output is:



















Mixing Instance and Static Members in the same Class

We can also define instance classes that have both, instance and static members such as: fields, properties, constructors, methods, etc. However, we cannot do that if the class is marked as static because of the features mentioned in the previous post:
The main features of a static class are:
  • They only contain static members.
  • They cannot be instantiated.
  • They are sealed.
  • They cannot contain Instance Constructors

namespace FiborialExtrasBoo2
import System

// Instance Classes can have both: static and instance members.   
// However, Static Classes only allow static members to be defined.  
// If you declare our next example class as static  
// (static class Fiborial) you will get the following compile error  
// Error: cannot declare instance members in a static class  
    
// Instance Class  
public class Fiborial:
    // Instance Field
    private instanceCount as int
    // Static Field
    private static staticCount as int
    // Instance Read-Only Property  
    // Within instance members, you can always use    
    // the "self" reference pointer to access your (instance) members.            
    public InstanceCount as int:
        get:
            return self.instanceCount  
    // Static Read-Only Property  
    // Remeber that Properties are Methods to the CLR, so, you can also  
    // define static properties for static fields.   
    // As with Static Methods, you cannot reference your class members  
    // with the "self" reference pointer since static members are not  
    // instantiated.          
    public static StaticCount as int:
        get:  
            return staticCount  
    // Instance Constructor  
    public def constructor():
        self.instanceCount = 0  
        print "\nInstance Constructor ${self.instanceCount}"
    // Static Constructor  
    private static def constructor():
        staticCount = 0  
        print "\nStatic Constructor ${staticCount}"
    // Instance Method
    public def Factorial(n as int) as void: 
        self.instanceCount += 1 
        print "\nFactorial(${n})" 
    // Static Method  
    public static def Fibonacci(n as int) as void: 
        staticCount += 1
        print "\nFibonacci(${n})" 

public def Main(argv as (string)):
    // Calling Static Constructor and Methods  
    // No need to instantiate  
    Fiborial.Fibonacci(5)
    
    // Calling Instance Constructor and Methods  
    // Instance required  
    fib as Fiborial = Fiborial()  
    fib.Factorial(5)
    
    Fiborial.Fibonacci(15)
    fib.Factorial(5)
    
    // Calling Instance Constructor and Methods  
    // for a second object  
    fib2 as Fiborial = Fiborial()
    fib2.Factorial(5)
    
    print ""
    // Calling Static Property  
    print "Static Count = ${Fiborial.StaticCount}"
    // Calling Instance Property of object 1 and 2  
    print "Instance 1 Count = ${fib.InstanceCount}"
    print "Instance 2 Count = ${fib2.InstanceCount}"
    Console.ReadKey(true)

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.

namespace FiborialExtrasBoo3
import System
import System.Diagnostics
import System.Numerics

# Long Factorial
def FactorialInt64(n as int) as long:
    if n == 1:
        return 1
    else:
        return n * FactorialInt64(n - 1)
    
# Double/Number Factorial   
def FactorialDouble(n as int) as double:
    if n == 1:
        return 1
    else:
        return n * FactorialDouble(n - 1)
 
# BigInteger Factorial   
def FactorialBigInteger(n as int) as BigInteger:  
    if n == 1:
        return 1
    else:
        return n * FactorialBigInteger(n - 1)

public def Main(argv as (string)):
    timer as Stopwatch = Stopwatch()
    facIntResult as long = 0
    facDblResult as double = 0
    facBigResult as BigInteger = 0  
    i as int = 0
    
    print "\nFactorial using Int64"
    # Benchmark Factorial using Int64  
    # Overflow Exception!!!
    try:
        for i as int in range(5,55,5):
            timer.Start()
            facIntResult = FactorialInt64(i)
            timer.Stop()        
            print " (${i}) = ${timer.Elapsed} : ${facIntResult}"
    except ex as ArithmeticException:
        # yummy ^_^
        print "Oops! ${ex.Message} "
    
    print "\nFactorial using Double"
    # Benchmark Factorial using Double
    for i as int in range(5,55,5):
        timer.Start()
        facDblResult = FactorialDouble(i)
        timer.Stop()        
        print " (${i}) = ${timer.Elapsed} : ${facDblResult}"
    
    print "\nFactorial using BigInteger"
    # Benchmark Factorial using BigInteger
    for i as int in range(5,55,5):
        timer.Start()
        facBigResult = FactorialBigInteger(i)
        timer.Stop()        
        print " (${i}) = ${timer.Elapsed} : ${facBigResult}"
    
    Console.ReadKey(true)

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:

Sunday, March 6, 2011

Factorial and Fibonacci in F#



WARNING! I know that F# is intended to be use in a very Functional way, however, my goal is to show its Imperative and OO language features, so it can be compared with other 19 OO languages. Said that, if you know how to do something on the examples below in a more Functional style you can add it in a comment :)

Here below a little program in F# 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 

In F# like in VB.NET there is a type called Module. An F# module is a grouping of F# code constructs such as types, values, function values, and code in do bindings. It is implemented as a common language runtime (CLR) class that has only static members. Normally I would only use the Module type as the first example, however, here I included both, an instance class with only Static Members and a second example using Module. The syntax for the members declaration varies so I wanted to include both even if we see a second example in the Mixing Instance and Static members program.

The Fiborial Program (using Type = Instance Class)

// Factorial and Fibonacci in F#  
namespace FiborialFs  
open System    
open System.Collections.Generic  
open System.Diagnostics  
//open System.Numerics  
  
// Instance Class   
// with all static members   
type StaticFiborial() = class  
    // Static Field  
    static let mutable className:string = ""  
    // Static Constructor/Initializer(s)   
    static do className <- "Static Constructor"      
    static do printfn "%s" className      
    // Static Method - Factorial Recursive  
    // in F#: type bigint = BigInteger  
    static member public FactorialR(n:int) : bigint =  
        if n = 1 then   
            bigint(1)  
        else   
            bigint(n) * StaticFiborial.FactorialR(n-1)  
    // Static Method - Factorial Imperative  
    static member public FactorialI(n:int) : bigint =  
        let mutable res:bigint = bigint(1)  
        for i = n downto 1 do   
            res <- res * bigint(i)  
        res  
    // Static Method - Fibonacci Recursive  
    static member public FibonacciR(n:int) : int64 =  
        if (n < 2) then  
            int64(1)  
        else    
            StaticFiborial.FibonacciR (n - 1) + StaticFiborial.FibonacciR(n - 2)  
    // Static Method - Fibonacci Imperative  
    static member public FibonacciI(n:int) : int64 =  
        let mutable pre:int64 = int64(1)  
        let mutable cur:int64 = int64(1)  
        let mutable tmp:int64 = int64(0)  
        for i = 2 to n do  
            tmp <- cur + pre  
            pre <- cur  
            cur <- tmp  
        cur  
    // Static Method - Benchmarking Algorithms  
    static member public BenchmarkAlgorithm(algorithm:int, values:list<int>) =  
        let timer = new Stopwatch()  
        let mutable i:int = 0  
        let mutable testValue:int = 1  
        let mutable facTimeResult:bigint = bigint(0)  
        let mutable fibTimeResult:int64 = int64(0)  
  
        // "if-elif-else" Flow Control Statement  
        if algorithm = 1 then  
            printfn "\nFactorial Imperative:"   
            // "For to" Loop Statement  
            for i = 0 to values.Length - 1 do  
                testValue <- values.Item(i)  
                // Taking Time    
                timer.Start()  
                facTimeResult <- StaticFiborial.FactorialI testValue
                timer.Stop()  
                // Getting Time    
                printfn " (%A) = %A" testValue timer.Elapsed
  
        elif algorithm = 2 then  
            printfn "\nFactorial Recursive:"   
            // "While" Loop Statement  
            while i < values.Length do    
                testValue <- values.Item(i)  
                // Taking Time    
                timer.Start()  
                facTimeResult <- StaticFiborial.FactorialR testValue  
                timer.Stop()  
                // Getting Time    
                printfn " (%A) = %A" testValue timer.Elapsed
                i <- i + 1  
  
        elif algorithm = 3 then  
            printfn "\nFibonacci Imperative:"  
            // "For in" Loop Statement  
            for item in values do  
                testValue <- item  
                // Taking Time    
                timer.Start()    
                fibTimeResult <- StaticFiborial.FibonacciI(testValue)  
                timer.Stop()    
                // Getting Time    
                printfn " (%A) = %A" testValue timer.Elapsed
  
        elif algorithm = 4 then  
            printfn "\nFibonacci Recursive:"  
            // "For in" Loop Statement  
            for item in values do  
                testValue <- item  
                // Taking Time    
                timer.Start()
                fibTimeResult <- StaticFiborial.FibonacciR testValue
                timer.Stop()    
                // Getting Time    
                printfn " (%A) = %A" testValue timer.Elapsed
  
        else   
            printfn "DONG!"   
end   
  
// Instance Class    
type InstanceFiborial() = class     
        // Instance Field  
        let mutable className:string = ""  
        // Instance Constructor/Initializer(s)   
        do className <- "Instance Constructor"  
        do printfn "%s" className  
        // Instance Method - Factorial Recursive    
        member public self.FactorialR(n:int) : bigint =  
            // Calling Static Method    
            StaticFiborial.FactorialR n    
        // Instance Method - Factorial Imperative    
        member public self.FactorialI(n:int) : bigint =  
            // Calling Static Method    
            StaticFiborial.FactorialI n
        // Instance Method - Fibonacci Recursive    
        member public self.FibonacciR(n:int) : int64 =  
            // Calling Static Method    
            StaticFiborial.FibonacciR n
        // Instance Method - Factorial Imperative    
        member public self.FibonacciI(n:int) : int64 =  
            // Calling Static Method    
            StaticFiborial.FibonacciI n    
end  

 
module Program =   
    //printfn "%s" (Fiborial.FactorialR(40).ToString())  
    printfn "\nStatic Class"  
    // Calling Instance Class with Static Methods    
    // No instantiation needed. Calling method directly from the class        
    printfn "FacImp(5) = %A" (StaticFiborial.FactorialI 5)
    printfn "FacRec(5) = %A" (StaticFiborial.FactorialR 5)  
    printfn "FibImp(11)= %i" (StaticFiborial.FibonacciI 11)
    printfn "FibRec(11)= %i" (StaticFiborial.FibonacciR 11)
    
    printfn "\nInstance Class"  
    // Calling Instance Class and Methods     
    // Need to instantiate before using. Calling method from instantiated object    
    let ff = new InstanceFiborial()    
    printfn "FacImp(5) = %A" (ff.FactorialI 5)
    printfn "FacRec(5) = %A" (ff.FactorialR 5)  
    printfn "FibImp(11)= %i" (ff.FibonacciI 11)
    printfn "FibRec(11)= %i" (ff.FibonacciR 11)
    
    // Create a (generic) list of integer values to test    
    // From 5 to 50 by 5    
    let values = [5..5..50]  
      
    // 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    
    Console.Read() |> ignore

And the Output is:





































The Fiborial Program (using Module = Static Class)
// Factorial and Fibonacci in F#  
namespace FiborialFs  
open System    
open System.Collections.Generic  
open System.Diagnostics  
  
// Static Class   
module StaticFiborial =   
    // Static Field  
    let mutable className:string = ""  
    // Static Constructor/Initializer(s)   
    do className <- "Static Constructor"      
    do printfn "%s" className      
    // Static Method - Factorial Recursive  
    // in F#: type bigint = BigInteger  
    let rec FactorialR(n:int) : bigint =  
        if n = 1 then   
            bigint(1)  
        else   
            bigint(n) * FactorialR(n-1)  
    // Static Method - Factorial Imperative  
    let public FactorialI(n:int) : bigint =  
        let mutable res:bigint = bigint(1)  
        for i = n downto 1 do   
            res <- res * bigint(i)  
        res  
    // Static Method - Fibonacci Recursive  
    let rec FibonacciR(n:int) : int64 =  
        if (n < 2) then  
            int64(1)  
        else    
            FibonacciR(n - 1) + FibonacciR(n - 2)  
    // Static Method - Fibonacci Imperative  
    let public FibonacciI(n:int) : int64 =  
        let mutable pre:int64 = int64(1)  
        let mutable cur:int64 = int64(1)  
        let mutable tmp:int64 = int64(0)  
        for i = 2 to n do  
            tmp <- cur + pre  
            pre <- cur  
            cur <- tmp  
        cur  
    // Static Method - Benchmarking Algorithms  
    let public BenchmarkAlgorithm(algorithm:int, values:list<int>) =  
        let timer = new Stopwatch()  
        let mutable i:int = 0 
        let mutable testValue:int = 1  
  
        // "if-elif-else" Flow Control Statement  
        if algorithm = 1 then  
            printfn "\nFactorial Imperative:"   
            // "For to" Loop Statement  
            for i = 0 to values.Length - 1 do  
                testValue <- values.Item(i)  
                // Taking Time    
                timer.Start()  
                FactorialI testValue |> ignore
                timer.Stop()  
                // Getting Time    
                printfn " (%A) = %A" testValue timer.Elapsed
  
        elif algorithm = 2 then  
            printfn "\nFactorial Recursive:"   
            // "While" Loop Statement  
            while i < values.Length - 1 do    
                testValue <- values.Item(i)  
                // Taking Time    
                timer.Start()  
                FactorialR testValue |> ignore
                timer.Stop()  
                // Getting Time    
                printfn " (%A) = %A" testValue timer.Elapsed
                i <- i + 1  
  
        elif algorithm = 3 then  
            printfn "\nFibonacci Imperative:"  
            // "For in" Loop Statement  
            for item in values do  
                testValue <- item  
                // Taking Time    
                timer.Start()    
                FibonacciI testValue |> ignore
                timer.Stop()    
                // Getting Time    
                printfn " (%A) = %A" testValue timer.Elapsed
  
        elif algorithm = 4 then  
            printfn "\nFibonacci Recursive:"  
            // "For in" Loop Statement  
            for item in values do  
                testValue <- item  
                // Taking Time    
                timer.Start()    
                FibonacciR testValue |> ignore
                timer.Stop()    
                // Getting Time    
                printfn " (%A) = %A" testValue timer.Elapsed
  
        else   
            printfn "DONG!"   
  
module Program =   
    printfn "\nStatic Class"  
    // Calling Instance Class with Static Methods    
    // No instantiation needed. Calling method directly from the class    
    printfn "FacImp(5) = %A" (StaticFiborial.FactorialI 5)
    printfn "FacRec(5) = %A" (StaticFiborial.FactorialR 5)  
    printfn "FibImp(11)= %i" (StaticFiborial.FibonacciI 11)
    printfn "FibRec(11)= %i" (StaticFiborial.FibonacciR 11)
  
    // Create a (generic) list of integer values to test    
    // From 5 to 50 by 5    
    let values = [5..5..50]  
      
    // 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    
    Console.Read() |> ignore


And the Output is:




































Printing the Factorial and Fibonacci Series
// Factorial and Fibonacci in F#  
namespace FiborialSeries  
open System    
open System.Text  
open System.Numerics  
  
// Static Class   
module Fiborial =   
    // We first define the Factorial and Fibonacci methods  
    // so we can use them after in the Series methods  
  
    let rec Factorial(n:int) : bigint =  
        if n = 1 then   
            bigint(1)  
        else   
            bigint(n) * Factorial(n-1)  
  
    let rec Fibonacci(n:int) : int64 =  
        if (n < 2) then  
            int64(1)  
        else    
            Fibonacci(n - 1) + Fibonacci(n - 2)  
  
    // Using a StringBuilder as a list of string elements    
    let public GetFactorialSeries(n:int): string =  
        // Create the String that will hold the list    
        let mutable series:StringBuilder = StringBuilder()  
        // We begin by concatenating the number you want to calculate    
        // in the following format: "!# ="    
        ignore (series.Append "!")  
        ignore (series.Append n)  
        ignore (series.Append " = ")  
        // We iterate backwards through the elements of the series   
        for i = n downto 1 do   
            // and append it to the list    
            ignore (series.Append i)  
            if i > 1 then  
                ignore (series.Append " * ")  
            else  
                ignore (series.Append " = ")  
        // Get the result from the Factorial Method    
        // and append it to the end of the list    
        ignore (series.Append(Factorial n))    
        // return the list as a string    
        series.ToString()  
  
    // Using a StringBuilder as a list of string elements   
    let public GetFibonnaciSeries(n:int): string =  
        // Create the String that will hold the list   
        let mutable series:StringBuilder = StringBuilder()  
        // We begin by concatenating the first 3 values which    
        // are always constant    
        ignore (series.Append "0, 1, 1")  
        // Then we calculate the Fibonacci of each element    
        // and add append it to the list   
        for i = 2 to n do  
            if i < n then  
                ignore (series.Append ", ")  
            else  
                ignore (series.Append " = ")  
            ignore (series.Append(Fibonacci i))  
        // return the list as string  
        series.ToString()  
  
module Program =  
    // Printing Factorial Series    
    printfn ""    
    printfn "%s" (Fiborial.GetFactorialSeries 5)  
    printfn "%s" (Fiborial.GetFactorialSeries 7)    
    printfn "%s" (Fiborial.GetFactorialSeries 9)  
    printfn "%s" (Fiborial.GetFactorialSeries 11)    
    printfn "%s" (Fiborial.GetFactorialSeries 40)    
    // Printing Fibonacci Series    
    printfn ""    
    printfn "%s" (Fiborial.GetFibonnaciSeries 5)  
    printfn "%s" (Fiborial.GetFibonnaciSeries 7)  
    printfn "%s" (Fiborial.GetFibonnaciSeries 9)  
    printfn "%s" (Fiborial.GetFibonnaciSeries 11)  
    printfn "%s" (Fiborial.GetFibonnaciSeries 40)

And the Output is:

















Mixing Instance and Static Members in the same Class

We can also define instance classes that have both, instance and static members such as: fields, properties, constructors, methods, etc. However, we cannot do that if the type is a Module because Module = Static Class and remember the features mentioned in the previous post:
The main features of a static class are:
  • They only contain static members.
  • They cannot be instantiated.
  • They are sealed.
  • They cannot contain Instance Constructors

namespace FiborialExtrasFs2  
open System  
  
// Instance Classes can have both: static and instance members.     
// However, Modules (Static Classes) only allow static members to be defined.    
  
// Instance Class    
type Fiborial() = class  
    // Instance Field  
    let mutable instanceCount:int = 0  
    // Instance Constructor/Initializer(s)   
    do instanceCount <- 0  
    do printfn "\nInstance Constructor %i" instanceCount
    // Static Field  
    static let mutable staticCount:int = 0  
    // Static Constructor/Initializer(s)   
    static do staticCount <- 0  
    static do printfn "\nStatic Constructor %i" Fiborial.StaticCount    
    // Instance Read-Only Property  
    member public this.InstanceCount   
        with get() = instanceCount  
    // Static Read-Only Property    
    // Remeber that Properties are Methods to the CLR, so, you can also    
    // define static properties for static fields.     
    static member public StaticCount  
        with get() = staticCount  
    // Instance Method  
    member public this.Factorial(n:int) =  
        instanceCount <- instanceCount + 1  
        printfn "\nFactorial(%i)" instanceCount
    // Static Method  
    static member public Fibonacci(n:int) =  
        staticCount <- staticCount + 1  
        printfn "\nFibonacci(%i)" Fiborial.StaticCount
end  
  
module Program =  
    // Calling Static Constructor and Methods    
    // No need to instantiate    
    Fiborial.Fibonacci 5
    
    // Calling Instance Constructor and Methods    
    // Instance required    
    let fib:Fiborial = new Fiborial()  
    fib.Factorial 5
    
    Fiborial.Fibonacci 15
    fib.Factorial 5
    
    // Calling Instance Constructor and Methods    
    // for a second object    
    let fib2:Fiborial = new Fiborial()  
    fib2.Factorial 5    
                
    printfn ""  
    // Calling Static Property    
    printfn "Static Count = %i" Fiborial.StaticCount  
    // Calling Instance Property of object 1 and 2    
    printfn "Instance 1 Count = %i" fib.InstanceCount
    printfn "Instance 2 Count = %i" fib2.InstanceCount

And the Output is:





















Factorial using System.Int64, System.Double, System.Numerics.BigInteger (bigint)

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 execution thrown an Overflow Exception when using the "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 said, lets have a look at the following code and the output we get.

open System  
open System.Diagnostics  
  
// Long Factorial  
let rec FactorialInt64(n:int): int64 =  
    match n with  
    | 1 -> int64(1)  
    | n -> int64(n) * FactorialInt64(n - 1)  
  
// Double Factorial  
let rec FactorialDouble(n:int): double =  
    match n with  
    | 1 -> double(1)  
    | n -> double(n) * FactorialDouble(n - 1)  
  
// BigInteger Factorial  
let rec FactorialBigInteger(n:int): bigint =  
    match n with  
    | 1 -> bigint(1)  
    | n -> bigint(n) * FactorialBigInteger(n - 1)  
  
let timer:Stopwatch = new Stopwatch()  
let mutable facIntResult:int64 = int64(0)  
let mutable facDblResult:double = double(0)  
let mutable facBigResult:bigint = bigint(0)  
  
let values:list<int> = [5..5..50]  
  
printfn "\nFactorial using Int64"  
// Benchmark Factorial using Int64  
for i in values do  
    timer.Start()    
    facIntResult <- FactorialInt64(i)  
    timer.Stop()   
    printfn "(%i) = %A : %i" i timer.Elapsed facIntResult
  
printfn "\nFactorial using Double"  
// Benchmark Factorial using Double  
for i in values do  
    timer.Start()    
    facDblResult <- FactorialDouble(i)  
    timer.Stop()   
    printfn "(%i) = %A : %E" i timer.Elapsed facDblResult
  
printfn "\nFactorial using BigInteger"  
// Benchmark Factorial using Double  
for i in values do  
    timer.Start()  
    facBigResult <- FactorialBigInteger(i)  
    timer.Stop()   
    printfn "(%i) = %A : %A" i timer.Elapsed facBigResult

NOTE: you DONT need to manually add a reference to the System.Numerics.dll assembly to your project because F# already adds it for you. In fact you don't need to use BigInteger, but bigint which is a type bigint = BigInteger.

And the Output is:

Friday, March 4, 2011

Factorial and Fibonacci in JScript.NET



Here below a little program in JScript.NET 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

// Factorial and Fibonacci in JScript.NET
import System;  
// JScript does not support the use of generics
// import System.Collections.Generic;
import System.Collections;
import System.Diagnostics;
import System.Numerics;
 
package FiborialJs {     
    // Instance Class     
    // static is not a class modifier in JScript
    public class StaticFiborial {
        // Static Field
        static var className : String;
        // Static Initializer (Static Constructor)
        static StaticFiborial {
            className = 'Static Constructor';
            Console.WriteLine(className);            
        }
        // Static Method - Factorial Recursive
        static function FactorialR(n : int) : BigInteger {
            if (n == 1)
                // cannot use return 1 because literal 1 is
                // not a BigNumber and cannot convert! 
                return new BigInteger(1);
            else
                return n * FactorialR(n - 1);
        }
        // Static Method - Factorial Imperative
        static function FactorialI(n : int) : BigInteger {
            // cannot use var res : BigInteger = 1; because 
            // literal 1 is not a BigNumber and cannot convert! 
            var res : BigInteger = new BigInteger(1);
            for (var i : int = n; i >= 1; i--) {
                res *= i;
            }
            return res;
        }
        // Static Method - Fibonacci Recursive
        static function FibonacciR(n : int) : long {
            if (n < 2)
                return 1;
            else
                return FibonacciR(n - 1) + FibonacciR(n - 2);
        }
        // Static Method - Fibonacci Imperative
        static function FibonacciI(n : int) : long {
            var pre : long, cur : long, tmp : long = 0;
            pre = cur = 1;            
            for (var i : int = 2; i <= n; i++) {
                tmp = cur + pre;
                pre = cur;
                cur = tmp;
            }
            return cur;
        }
        // Static Method - Benchmarking Algorithms
        static function BenchmarkAlgorithm(algorithm : int, values : ArrayList) {
            var timer : Stopwatch = new Stopwatch;
            var i : int = 0, testValue : int = 0;
            var facTimeResult : BigInteger = new BigInteger(0);
            var fibTimeResult : long = 0;
            
            // 'Switch' Flow Constrol Statement
            switch (algorithm)
            {
                case 1:
                    Console.WriteLine('\nFactorial Imperative:');
                    // 'For' Loop Statement
                    for (i = 0; i < values.Count; i++) {                        
                        testValue = values[i];
                        // Taking Time
                        timer.Start();
                        facTimeResult = FactorialI(testValue);
                        timer.Stop();                        
                        // Getting Time
                        Console.WriteLine(' ({0}) = {1}', testValue, timer.Elapsed);
                    }                    
                    break;
                case 2:
                    Console.WriteLine('\nFactorial Recursive:');
                    // 'While' Loop Statement
                    while (i < values.Count) {                        
                        testValue = values[i];
                        // Taking Time
                        timer.Start();
                        facTimeResult = FactorialR(testValue);
                        timer.Stop();
                        // Getting Time
                        Console.WriteLine(' ({0}) = {1}', testValue, timer.Elapsed);
                        i++;
                    }
                    break;
                case 3:
                    Console.WriteLine('\nFibonacci Imperative:');
                    // 'Do-While' Loop Statement
                    do {
                        testValue = values[i];
                        // Taking Time
                        timer.Start();
                        fibTimeResult = FibonacciI(testValue);
                        timer.Stop();
                        // Getting Time
                        Console.WriteLine(' ({0}) = {1}', testValue, timer.Elapsed);
                        i++;
                    } while (i < values.Count);
                    break;
                case 4:
                    Console.WriteLine('\nFibonacci Recursive:');
                    // 'For In' Loop Statement
                    for (var item : int in values) {
                        testValue = item;
                        // Taking Time
                        timer.Start();
                        fibTimeResult = FibonacciR(testValue);
                        timer.Stop();
                        // Getting Time
                        Console.WriteLine(' ({0}) = {1}', testValue, timer.Elapsed);
                    }
                    break;
                default:
                    Console.WriteLine('DONG!');
                    break;
            }            
        }        
    }

    // Instance Class
    public class InstanceFiborial {
        // Instance Field
        var className : String;
        // Instance Constructor
        function InstanceFiborial() {
            this.className = 'Instance Constructor';
            Console.WriteLine(this.className);
        }
        // Instance Method - Factorial Recursive
        function FactorialR(n : int) : BigInteger {
            // Calling Static Method
            return StaticFiborial.FactorialR(n);
        }
        // Instance Method - Factorial Imperative
        function FactorialI(n : int) : BigInteger {
            // Calling Static Method
            return StaticFiborial.FactorialI(n);
        }
        // Instance Method - Fibonacci Recursive
        function FibonacciR(n : int) : long {
            // Calling Static Method
            return StaticFiborial.FibonacciR(n);
        }
        // Instance Method - Factorial Imperative
        function FibonacciI(n : int) : long {
            // Calling Static Method
            return StaticFiborial.FibonacciI(n);
        }
    };
};

import FiborialJs;

function Main() {
    Console.WriteLine('\nInstance Class with Static Methods only');
    // Calling Static Methods from an Instance Class
    // No instantiation needed. Calling method directly from the class
    Console.WriteLine('FacImp(5) = {0}', StaticFiborial.FactorialI(5));
    Console.WriteLine('FacRec(5) = {0}', StaticFiborial.FactorialR(5));
    Console.WriteLine('FibImp(11)= {0}', StaticFiborial.FibonacciI(11));
    Console.WriteLine('FibRec(11)= {0}', StaticFiborial.FibonacciR(11));

    Console.WriteLine('\nInstance Class');
    // Calling Instance Class and Methods 
    // Need to instantiate before using. Calling method from instantiated object
    var ff : InstanceFiborial = new InstanceFiborial;
    Console.WriteLine('FacImp(5) = {0}', ff.FactorialI(5));
    Console.WriteLine('FacRec(5) = {0}', ff.FactorialR(5));
    Console.WriteLine('FibImp(11)= {0}', ff.FibonacciI(11));
    Console.WriteLine('FibRec(11)= {0}', ff.FibonacciR(11));

    // Create na arraylist of integer values to test
    // From 5 to 50 by 5
    //var values : List<int> = new List<int>;
    var values : ArrayList = new ArrayList;
    for(var i : int = 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
    Console.Read();
};

Main();

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
import System;  
import System.Text;
import System.Numerics;

package FiborialSeries {
    class Fiborial {
        // Using a StringBuilder as a list of string elements
        public static function GetFactorialSeries(n : int) : String {
            // Create the String that will hold the list
            var series : StringBuilder = 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 (var i : int = 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(Factorial(n));
            // return the list as a string
            return series.ToString();
        }

        // Using a StringBuilder as a list of string elements
        public static function GetFibonnaciSeries(n : int) : String {
            // Create the String that will hold the list
            var series : StringBuilder = 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 (var i : int = 2; i <= n; i++) {
                if (i < n)
                    series.Append(', ');
                else
                    series.Append(' = ');
                
                series.Append(Fibonacci(i));
            }
            // return the list as a string
            return series.ToString();
        }

        public static function Factorial(n : int) : BigInteger {
            if (n == 1)                
                return new BigInteger(1);
            else
                return n * Factorial(n - 1);
        }

        public static function Fibonacci(n : int) : long {
            if (n < 2)
                return 1;
            else
                return Fibonacci(n - 1) + Fibonacci(n - 2);
        }
    }
}

import FiborialSeries;

// Printing Factorial Series
Console.WriteLine();
Console.WriteLine(Fiborial.GetFactorialSeries(5));
Console.WriteLine(Fiborial.GetFactorialSeries(7));
Console.WriteLine(Fiborial.GetFactorialSeries(9));
Console.WriteLine(Fiborial.GetFactorialSeries(11));
Console.WriteLine(Fiborial.GetFactorialSeries(40));
// Printing Fibonacci Series
Console.WriteLine();
Console.WriteLine(Fiborial.GetFibonnaciSeries(5));
Console.WriteLine(Fiborial.GetFibonnaciSeries(7));
Console.WriteLine(Fiborial.GetFibonnaciSeries(9));
Console.WriteLine(Fiborial.GetFibonnaciSeries(11));
Console.WriteLine(Fiborial.GetFibonnaciSeries(40));

And the Output is:



















Mixing Instance and Static Members in the same Class

We can also define instance classes that have both, instance and static members such as: fields, properties, constructors/initializers, methods, etc. However, we cannot do that if the class is marked as static because JScript.NET does not support it. The following text explains why:

"The static modifier signifies that a member belongs to the class itself rather than to instances of the class. Only one copy of a static member exists in a given application even if many instances of the class are created. You can only access static members with a reference to the class rather than a reference to an instance. However, within a class member declaration, static members can be accessed with the this object.

Members of classes can be marked with the static modifier. Classes, interfaces, and members of interfaces cannot take the static modifier.

You may not combine the static modifier with any of the inheritance modifiers (abstract and final) or version-safe modifiers (hide and override).

Do not confuse the static modifier with the static statement. The static modifier denotes a member that belongs to the class itself rather than any instance of the class." Taken from:

on the other hand:

"A static initializer is used to initialize a class object (not object instances) before its first use. This initialization occurs only once, and it can be used to initialize fields in the class that have the static modifier.

A class may contain several static initializer blocks interspersed with static field declarations. To initialize the class, all the static blocks and static field initializers are executed in the order in which they appear in the class body. This initialization is performed before the first reference to a static field.

Do not confuse the static modifier with the static statement. The static modifier denotes a member that belongs to the class itself, not any instance of the class." Taken from:

import System;

package FiborialExtrasJs2 {
    // Instance Classes can have both: static and instance members. 
    // However, Static Classes only allow static members to be defined.
    // If you declare our next example class as static
    // (static class Fiborial) you will get the following compile error
    // Error: cannot declare instance members in a static class
    
    // Instance Class
    class Fiborial {
        // Instance Field
        private var instanceCount : int;
        // Static Field
        private static var staticCount : int;
        // Instance Read-Only Property
        // Within instance members, you can always use  
        // the 'this' reference pointer to access your (instance) members.
        public function get InstanceCount() : int {
            return this.instanceCount;
        }
        // Static Read-Only Property
        // Remeber that Properties are Methods to the CLR, so, you can also
        // define static properties for static fields. 
        // As with Static Methods, you cannot reference your class members
        // with the 'this' reference pointer since static members are not
        // instantiated.        
        public static function get StaticCount() : int {
            return staticCount;
        }
        // Instance Constructor
        public function Fiborial() {
            this.instanceCount = 0;
            Console.WriteLine('\nInstance Constructor {0}', this.instanceCount);
        }
        // Static Constructor
        static Fiborial {
            staticCount = 0;
            Console.WriteLine('\nStatic Constructor {0}', staticCount);
        }
        // Instance Method
        public function Factorial(n : int)
        {
            this.instanceCount += 1;
            Console.WriteLine('\nFactorial({0})', n);
        }
        // Static Method
        public static function Fibonacci(n : int)
        {
            staticCount += 1;
            Console.WriteLine('\nFibonacci({0})', n);
        }
    };       
};

import FiborialExtrasJs2;
// Calling Static Constructor and Methods
// No need to instantiate
Fiborial.Fibonacci(5);

// Calling Instance Constructor and Methods
// Instance required
var fib : Fiborial = new Fiborial;
fib.Factorial(5);

Fiborial.Fibonacci(15);
fib.Factorial(5);

// Calling Instance Constructor and Methods
// for a second object
var fib2 : Fiborial = new Fiborial;
fib2.Factorial(5);

Console.WriteLine();
// Calling Static Property
Console.WriteLine('Static Count = {0}', Fiborial.StaticCount);
// Calling Instance Property of object 1 and 2
Console.WriteLine('Instance 1 Count = {0}', fib.InstanceCount);
Console.WriteLine('Instance 2 Count = {0}', fib2.InstanceCount);

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 and JScript.NET 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.

import System;  
import System.Diagnostics;
import System.Numerics;
import Microsoft.JScript; // to get the JScriptException

// Long Factorial 
function FactorialInt64(n : int) : long {
    if (n == 1)
        return 1;
    else
        return n * FactorialInt64(n - 1);
}

// Double/Number Factorial 
function FactorialDouble(n : int) : Number {
    if (n == 1)
        return 1;
    else
        return n * FactorialDouble(n - 1);
}

// BigInteger Factorial 
function FactorialBigInteger(n : int) : BigInteger {
    if (n == 1)
        return new BigInteger(1);
    else
        return n * FactorialBigInteger(n - 1);
}

function Main() {
    var timer : Stopwatch = new Stopwatch;
    var facIntResult : long = 0;
    var facDblResult : Number = 0;
    var facBigResult : BigInteger = new BigInteger(0);
    var i : int = 0;
    
    Console.WriteLine('\nFactorial using Int64');
    // Benchmark Factorial using Int64
    // Overflow Exception!!! 
    // in JScript case this is a JsScriptException
    try {
        for (i = 5; i <= 50; i += 5) {
            timer.Start();
            facIntResult = FactorialInt64(i);
            timer.Stop();
            Console.WriteLine(' ({0}) = {1} : {2}', i, timer.Elapsed, facIntResult);
        }
    } catch(ex : JScriptException) {
        // yummy ^_^  
        Console.WriteLine(' Oops! {0} ', ex.Message);
    }    
    Console.WriteLine('\nFactorial using Double');
    // Benchmark Factorial using Double/Number
    for (i = 5; i <= 50; i += 5) {
        timer.Start();
        facDblResult = FactorialDouble(i);
        timer.Stop();
        Console.WriteLine(' ({0}) = {1} : {2}', i, timer.Elapsed, facDblResult);
    }
    Console.WriteLine('\nFactorial using BigInteger');
    // Benchmark Factorial using BigInteger
    for (i = 5; i <= 50; i += 5) {
        timer.Start();
        facBigResult = FactorialBigInteger(i);
        timer.Stop();
        Console.WriteLine(' ({0}) = {1} : {2}', i, timer.Elapsed, facBigResult);
    }
}

Main();

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 in this particular case, you also need to reference Microsoft.JScript.dll assembly to get the JScriptException class.

And the Output is: