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:

No comments:

Post a Comment