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:

No comments:

Post a Comment