Saturday, February 26, 2011

Factorial and Fibonacci in Oxygene



Here below a little program in Oxygene 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 Delphi Prism
namespace FiborialDelphi;

interface
uses
    System,
    System.Diagnostics,
    System.Collections.Generic,
    System.Numerics;

type
    // Static Class 
    StaticFiborial = public static class
    private
        // Static/Class Field
        class var 
            fClassName: string;        
    public
        // Static/Class Constructor 
        class constructor;
        // Static/Class Method - Factorial Recursive    
        class method FactorialR(n: integer): BigInteger;
        // Static/Class Method - Factorial Imperative
        class method FactorialI(n: integer): BigInteger;
        // Static/Class Method - Fibonacci Recursive
        class method FibonacciR(n: integer): Int64;
        // Static/Class Method - Fibonacci Imperative
        class method FibonacciI(n: integer): Int64;
        // Static/Class Method - Benchmarking Algorithms 
        class method BenchmarkAlgorithm(algorithm: integer; values: List<integer>);
    end;

type
    // Instance Class 
    InstanceFiborial = public class
    private
        // Instance Field
        var
            fClassName: string;
    public
        // Instance Constructor 
        constructor;
        // Instance Method - Factorial Recursive    
        method FactorialR(n: integer): BigInteger;
        // Instance Method - Factorial Imperative
        method FactorialI(n: integer): BigInteger;
        // Instance Method - Fibonacci Recursive
        method FibonacciR(n: integer): Int64;
        // Instance Method - Fibonacci Imperative
        method FibonacciI(n: integer): Int64;
    end;

type
    ConsoleApp = class
    public
        class method Main(args: array of string);
    end;

implementation

// Static/Class Constructor   
class constructor StaticFiborial;
begin
    fClassName := 'Static/Class Constructor';
    Console.WriteLine(fClassName);
end;
// Static/Class Method - Factorial Recursive    
class method StaticFiborial.FactorialR(n: integer): BigInteger;
begin
    if n = 1 then 
        result := 1
    else 
        result := n * FactorialR(n - 1);
end;
// Static/Class Method - Factorial Imperative
class method StaticFiborial.FactorialI(n: integer): BigInteger;
var 
    res: BigInteger := 1;
begin
    for i:integer := n downto 1 step 1 do
        res := res * i;
    result := res;
end;
// Static/Class Method - Fibonacci Recursive
class method StaticFiborial.FibonacciR(n: integer): Int64;
begin
    if n < 2 then
        result := 1
    else
        result := FibonacciR(n - 1) + FibonacciR(n - 2);    
end;
// Static/Class Method - Fibonacci Imperative
class method StaticFiborial.FibonacciI(n: integer): Int64;
var
    tmp, pre, cur: Int64;        
begin    
    tmp := 0;
    pre := 1;
    cur := 1;
    for i: integer := 2 to n step 1 do
    begin
        tmp := cur + pre;
        pre := cur;
        cur := tmp;
    end;
    result := cur;
end;
// Static Method - Benchmarking Algorithms
class method StaticFiborial.BenchmarkAlgorithm(algorithm: integer; values: List<integer>);
var
    timer: StopWatch;
    i, testValue: integer;
    facTimeResult: BigInteger := 0;
    fibTimeResult: Int64 := 0;
begin
    i := 0;
    testValue := 0;
    timer := new StopWatch();
    // 'switch/case' Flow Constrol Statement 
    case algorithm of  
        1: begin
            Console.WriteLine(''#10'Factorial Imperative:');
            // 'For' Loop Statement
            for i := 0 to values.Count - 1 step 1 do
            begin
                testValue := values[i];
                // Taking Time    
                timer.Start();    
                facTimeResult := FactorialI(testValue);
                timer.Stop();                            
                // Getting Time    
                Console.WriteLine(' ({0}) = {1}', testValue, timer.Elapsed);
            end;
        end;
        2: begin
            Console.WriteLine(''#10'Factorial Recursive:');
            // 'While' Loop Statement 
            while i < values.Count do 
            begin
                testValue := values[i];
                // Taking Time    
                timer.Start();    
                facTimeResult := FactorialR(testValue);
                timer.Stop();                            
                // Getting Time    
                Console.WriteLine(' ({0}) = {1}', testValue, timer.Elapsed);
                inc(i);
            end;
        end;
        3: begin
            Console.WriteLine(''#10'Fibonacci Imperative:');
            // 'Repeat/Do' Loop Statement
            repeat        
                testValue := values[i];
                // Taking Time    
                timer.Start();    
                facTimeResult := FibonacciI(testValue);
                timer.Stop();
                // Getting Time    
                Console.WriteLine(' ({0}) = {1}', testValue, timer.Elapsed);
                inc(i);
            until i = values.Count - 1
        end;
        4: begin            
            Console.WriteLine(''#10'Fibonacci Recursive:');
            // 'For Each' Loop Statement
            for each item in values do
            begin
                testValue := item;  
                // Taking Time    
                timer.Start();    
                facTimeResult := FibonacciR(testValue);
                timer.Stop();
                // Getting Time    
                Console.WriteLine(' ({0}) = {1}', testValue, timer.Elapsed);
            end;
        end;
        else Console.WriteLine('DONG!');
    end;  
end;

// Instance Constructor   
constructor InstanceFiborial;
begin
    self.fClassName := 'Instance Constructor';
    Console.WriteLine(self.fClassName);
end;
// Instance Method - Factorial Recursive
method InstanceFiborial.FactorialR(n: integer): BigInteger;
begin
    // Calling Static Method    
    result := StaticFiborial.FactorialR(n);
end;
// Instance Method - Factorial Imperative
method InstanceFiborial.FactorialI(n: integer): BigInteger;
begin
    // Calling Static Method    
    result := StaticFiborial.FactorialI(n);
end;
// Instance Method - Fibonacci Recursive
method InstanceFiborial.FibonacciR(n: integer): Int64;
begin
    // Calling Static Method
    result := StaticFiborial.FibonacciR(n);
end;
// Instance Method - Fibonacci Imperative
method InstanceFiborial.FibonacciI(n: integer): Int64;
begin        
    // Calling Static Method
    result := StaticFiborial.FibonacciI(n);
end;

class method ConsoleApp.Main(args: array of string);
var
    values: List<integer>;
    ff: InstanceFiborial; 
begin
    Console.WriteLine(''#10'Static Class');
    // Calling Static Class and Methods  
    // 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(''#10'Instance Class');  
    // Calling Instance Class and Methods   
    // Need to instantiate before using. Calling method from instantiated object  
    ff := 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 a (generic) list of integer values to test  
    // From 5 to 50 by 5  
    values := new List<integer>();  
    for i:integer := 5 to 50 step 5 do
        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();  
end;

end.

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;

interface
uses
    System,
    System.Text,
    System.Numerics;

type
    Fiborial = static class
    public
        class method GetFactorialSeries(n: integer): string;
        class method GetFibonnaciSeries(n: integer): string;
        class method Factorial(n: integer): BigInteger;
        class method Fibonacci(n: integer): Int64;
    end;

type
    ConsoleApp = class
    public
        class method Main(args: array of string);
    end;

implementation

class method Fiborial.GetFactorialSeries(n: integer): string;
var
    // Using a StringBuilder as a list of string elements    
    series: StringBuilder;
begin
    // Create the String that will hold the list
    series := new StringBuilder();
    // We begin by concatenating the number you want to calculate
    // in the following format: "!# ="
    series.Append('!');
    series.Append(n);
    series.Append(' = ');
    // We iterate backwards through the elements of the series
    for i: integer := n downto 1 do
    begin
        // and append it to the list
        series.Append(i);
        if i > 1 then
            series.Append(' * ')
        else 
            series.Append(' = ');         
    end;
    // 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
    result := series.ToString();
end;

class method Fiborial.GetFibonnaciSeries(n: integer): string;
var
    // Using a StringBuilder as a list of string elements
    series: StringBuilder;
begin
    // Create the String that will hold the list
    series := new StringBuilder();
    // We begin by concatenating the first 3 values which
    // are always constant
    series.Append('0, 1, 1');
    // Then we calculate the Fibonacci of each element
    // and add append it to the list
    for i: integer := 2 to n do
    begin
        if i < n then
            series.Append(', ')
        else
            series.Append(' = ');
                
        series.Append(Fibonacci(i));
    end;
    // return the list as a string
    result := series.ToString();
end;

class method Fiborial.Factorial(n: integer): BigInteger;
begin
    if n = 1 then 
        result := 1
    else 
        result := n * Factorial(n - 1);
end;

class method Fiborial.Fibonacci(n: integer): Int64;
begin
    if n < 2 then
        result := 1
    else
        result := Fibonacci(n - 1) + Fibonacci(n - 2);    
end;

class method ConsoleApp.Main(args: array of string);
begin
    // 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));
    Console.Read();
end;

end.

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 FiborialExtrasDelphi2;
// 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
interface

// Instance Class
type Fiborial = class
    private
        // Instance Field
        var fInstanceCount: integer;
        // Static Field
        class var fStaticCount: integer;
    public
        // Instance Read-Only Property   
        // Within instance members, you can always use  
        // the "this" reference pointer to access your (instance) members.     
        property InstanceCount : integer read self.fInstanceCount;
        // 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.          
        class property StaticCount : integer read fStaticCount;
        // Instance Constructor
        constructor;
        // Static Constructor
        class constructor;
        // Instance Method
        method Factorial(n: integer);
        // Static Method
        class method Fibonacci(n: integer);
    end;

type ConsoleApp = class
    public
        class method Main(args: array of string);
    end;

implementation

// Instance Constructor   
constructor Fiborial;
begin
    self.fInstanceCount := 0;
    Console.WriteLine(''#10'Instance Constructor {0}', self.fInstanceCount);
end;
// Static/Class Constructor   
class constructor Fiborial;
begin
    fStaticCount := 0;
    Console.WriteLine(''#10'Static Constructor {0}', fStaticCount);
end;
// Instance Method
method Fiborial.Factorial(n: integer);
begin
    inc(self.fInstanceCount);
    Console.WriteLine(''#10'Factorial({0})', n);
end;
// Static Method
class method Fiborial.Fibonacci(n: integer);
begin
    inc(fStaticCount);
    Console.WriteLine(''#10'Fibonacci({0})', n);
end;

class method ConsoleApp.Main(args: array of string);
begin
    // Calling Static Constructor and Methods
    // No need to instantiate
    Fiborial.Fibonacci(5);

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

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

    // Calling Instance Constructor and Methods
    // for a second object
    var fib2 := 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);
    Console.Read();
end;

end.

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 on my previous post 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 "tried" to say, lets have a look at the following code and the output we get.

namespace FiborialExtrasDelphi3;

interface

uses   
    System,
    System.Numerics,
    System.Diagnostics;

type
    ConsoleApp = class
    public
        class method Main(args: array of string);
        class method FactorialInt64(n: integer): Int64;
        class method FactorialDouble(n: integer): Double;
        class method FactorialBigInteger(n: integer): BigInteger;
    end;

implementation

class method ConsoleApp.Main(args: array of string);
var
    timer: StopWatch;
    facIntResult: System.Int64 := 0;
    facDblResult: System.Double := 0;
    facBigResult: System.Numerics.BigInteger := 0;

begin
    timer := new StopWatch();
    Console.WriteLine(''#10'Factorial using Int64');    
    for i: integer := 5 to 50 step 5 do
    begin                
        timer.Start();
        facIntResult := FactorialInt64(i);
        timer.Stop();                                    
        Console.WriteLine(' ({0}) = {1} : {2}', i, timer.Elapsed, facIntResult);
    end;
    Console.WriteLine(''#10'Factorial using Double');
    for i: integer := 5 to 50 step 5 do
    begin                
        timer.Start();
        facDblResult := FactorialDouble(i);
        timer.Stop();                                    
        Console.WriteLine(' ({0}) = {1} : {2}', i, timer.Elapsed, facDblResult);
    end;
    Console.WriteLine(''#10'Factorial using BigInteger');
    for i: integer := 5 to 50 step 5 do
    begin                
        timer.Start();
        facBigResult := FactorialBigInteger(i);
        timer.Stop();                                    
        Console.WriteLine(' ({0}) = {1} : {2}', i, timer.Elapsed, facBigResult);
    end;
    Console.Read();
end;

class method ConsoleApp.FactorialInt64(n: integer): Int64;
begin
    if n = 1 then 
        result := 1
    else 
        result := n * FactorialInt64(n - 1);
end;

class method ConsoleApp.FactorialDouble(n: integer): Double;
begin
    if n = 1 then 
        result := 1
    else 
        result := n * FactorialDouble(n - 1);
end;

class method ConsoleApp.FactorialBigInteger(n: integer): BigInteger;
begin
    if n = 1 then 
        result := 1
    else 
        result := n * FactorialBigInteger(n - 1);
end;

end.

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:

Friday, February 25, 2011

Factorial and Fibonacci in C++/CLI



Here below a little program in C++/CLI 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 C++/CLI
#include "stdafx.h"
using namespace System;
using namespace System::Collections::Generic;
using namespace System::Diagnostics;
using namespace System::Numerics;

namespace FiborialCpp {
 // static class
 static ref class StaticFiborial {
 private:
  // Static Field
  static String^ className;
  // Static Constructor  
  static StaticFiborial() {  
   className = L"Static Constructor";  
   Console::WriteLine(className);              
  }  

 public:
  // Static Method - Factorial Recursive  
  static BigInteger FactorialR(int n) {  
   if (n == 1)
    return 1;
   else  
    return n * FactorialR(n - 1);
  }  
  // Static Method - Factorial Imperative  
  static BigInteger FactorialI(int n) {  
   BigInteger res = 1;  
   for (int i = n; i >= 1; i--) {
    res *= i;
   }
   return res;  
  }  
  // Static Method - Fibonacci Recursive  
  static long FibonacciR(int n) {  
   if (n < 2)  
    return 1;  
   else  
    return FibonacciR(n - 1) + FibonacciR(n - 2);  
  }  
  // Static Method - Fibonacci Imperative  
  static long FibonacciI(int n) {              
   long pre, cur, tmp = 0;  
   pre = cur = 1;              
   for (int i = 2; i <= n; i++) {  
    tmp = cur + pre;  
    pre = cur;  
    cur = tmp;  
   }  
   return cur;  
  }
  // Static Method - Benchmarking Algorithms  
  static void BenchmarkAlgorithm(int algorithm, List<int>^ values) {              
   Stopwatch ^timer = gcnew Stopwatch();  
   int i, testValue;  
   BigInteger facTimeResult = 0;  
   long fibTimeResult = 0;  
   i = testValue = 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 Each" Loop Statement  
     for each (int item 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(L"DONG!");  
     break;  
   }                  
  }  
 };

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

int main(array<System::String ^> ^args)
{ 
 Console::WriteLine("\nStatic Class");  
    // Calling Static Class and Methods  
    // No instantiation needed. Calling method directly from the class  
    Console::WriteLine("FacImp(5) = {0}", FiborialCpp::StaticFiborial::FactorialI(5));  
    Console::WriteLine("FacRec(5) = {0}", FiborialCpp::StaticFiborial::FactorialR(5));  
    Console::WriteLine("FibImp(11)= {0}", FiborialCpp::StaticFiborial::FibonacciI(11));  
    Console::WriteLine("FibRec(11)= {0}", FiborialCpp::StaticFiborial::FibonacciR(11));  
  
    Console::WriteLine("\nInstance Class");  
    // Calling Instance Class and Methods   
    // Need to instantiate before using. Calling method from instantiated object  
 FiborialCpp::InstanceFiborial ^ff = gcnew FiborialCpp::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 a (generic) list of integer values to test  
    // From 5 to 50 by 5  
    List<int> ^values = gcnew List<int>();  
    for(int i = 5; i <= 50; i += 5)  
        values->Add(i);  
  
    // Benchmarking Fibonacci                       
    // 1 = Factorial Imperative              
    FiborialCpp::StaticFiborial::BenchmarkAlgorithm(1, values);  
    // 2 = Factorial Recursive  
    FiborialCpp::StaticFiborial::BenchmarkAlgorithm(2, values);   
  
    // Benchmarking Factorial              
    // 3 = Fibonacci Imperative  
    FiborialCpp::StaticFiborial::BenchmarkAlgorithm(3, values);  
    // 4 = Fibonacci Recursive  
    FiborialCpp::StaticFiborial::BenchmarkAlgorithm(4, values);   
  
    // Stop and Exit  
    Console::Read();  

 return 0;
}

And the Output is:


































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

Printing the Factorial and Fibonacci Series
#include "stdafx.h"

using namespace System;
using namespace System::Text;
using namespace System::Numerics;  
 
namespace FiborialSeries {      

 static ref class Fiborial {  
 public:
  // Using a StringBuilder as a list of string elements  
  static String^ GetFactorialSeries(int n) {  
   // Create the String that will hold the list  
   StringBuilder ^series = gcnew 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 (int i = n; i <= n && i > 0; i--) {  
    // and append it to the list  
    series->Append(i);  
    if (i > 1)  
     series->Append(" * ");  
    else   
     series->Append(" = ");   
   }  
   // Get the result from the Factorial Method  
   // and append it to the end of the list  
   series->Append(Factorial(n));  
   // return the list as a string  
   return series->ToString();  
  }  
  
  // Using a StringBuilder as a list of string elements  
  static String^ GetFibonnaciSeries(int n)  
  {  
   // Create the String that will hold the list  
   StringBuilder ^series = gcnew 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 (int i = 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();  
  }  
  
  static BigInteger Factorial(int n)  
  {  
   if (n == 1)  
    return 1;  
   else  
    return n * Factorial(n - 1);  
  }  
  
  static long Fibonacci(int n)  
  {  
   if (n < 2)  
    return 1;  
   else  
    return Fibonacci(n - 1) + Fibonacci(n - 2);  
  }    
 };  
};

using namespace FiborialSeries;
int main(array<System::String ^> ^args)
{
 // 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));  
 Console::Read();
 return 0;
}

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

#include "stdafx.h"

using namespace System;

namespace FiborialExtrasCpp2 {  
 // 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  
 ref class Fiborial {  
 // Instance Field  
  private:
   int instanceCount;  
 // Static Field  
 static int staticCount;   
 
 public:
  // Instance Read-Only Property  
  // Within instance members, you can always use
  // the "this" reference pointer to access your (instance) members.  s
  property int InstanceCount {  
   int get() { 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.  
  static property int StaticCount {  
   int get() { return staticCount; }  
  }
  // Instance Constructor  
  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  
  void Factorial(int n) {  
   this->instanceCount += 1;  
   Console::WriteLine("\nFactorial({0})", n);  
  }
  // Static Method  
  static void Fibonacci(int n) {  
   staticCount += 1;  
   Console::WriteLine("\nFibonacci({0})", n);  
  }
 };  
};

using namespace FiborialExtrasCpp2;
int main(array<System::String ^> ^args)
 {
 // Calling Static Constructor and Methods  
 // No need to instantiate  
 Fiborial::Fibonacci(5);
  
 // Calling Instance Constructor and Methods  
 // Instance required  
 Fiborial ^fib = gcnew Fiborial();  
 fib->Factorial(5);
  
 Fiborial::Fibonacci(15);  
 fib->Factorial(5);  
  
 // Calling Instance Constructor and Methods  
 // for a second object  
 Fiborial ^fib2 = gcnew 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);
 Console::Read();
 return 0;
}

And the Output is:






















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

The Factorial of numbers over 20 are massive!
For instance: !40 = 815915283247897734345611269596115894272000000000!
Because of this, the previous version of this program was giving the "wrong" result
!40 = -70609262346240000 when using "long" (System::Int64) type, but it was on my previous post 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 "tried" to say, lets have a look at the following code and the output we get.

#include "stdafx.h"

using namespace System;
using namespace System::Numerics;
using namespace System::Diagnostics;

// Long Factorial   
static Int64 FactorialInt64(int n) {  
    if (n == 1)  
        return 1;  
    else  
        return n * FactorialInt64(n - 1);  
}  
  
// Double Factorial   
static Double FactorialDouble(int n) {  
    if (n == 1)  
        return 1;  
    else  
        return n * FactorialDouble(n - 1);  
}  
          
// BigInteger Factorial   
static BigInteger FactorialBigInteger(int n) {  
    if (n == 1)  
        return 1;  
    else  
        return n * FactorialBigInteger(n - 1);  
}  

int main(array<System::String ^> ^args) {
    Stopwatch ^timer = gcnew Stopwatch();
    Int64 facIntResult = 0;  
    Double facDblResult = 0;  
    BigInteger facBigResult = 0;  
  
    Console::WriteLine("\nFactorial using Int64");  
    // Benchmark Factorial using Int64  
    for (int i = 5; i <= 50; i += 5)  
    {  
        timer->Start();  
        facIntResult = FactorialInt64(i);  
        timer->Stop();  
        Console::WriteLine(" ({0}) = {1} : {2}", i, timer->Elapsed, facIntResult);  
    }  
    Console::WriteLine("\nFactorial using Double");  
    // Benchmark Factorial using Double  
    for (int 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 (int i = 5; i <= 50; i += 5)  
    {  
        timer->Start();  
        facBigResult = FactorialBigInteger(i);  
        timer->Stop();  
        Console::WriteLine(" ({0}) = {1} : {2}", i, timer->Elapsed, facBigResult);
    }
 Console::Read();
    return 0;
}

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


And the Output is:

Saturday, February 19, 2011

Factorial and Fibonacci in VB.NET



Here below a little program in VB.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 (or shared in VB.NET) 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 VB.NET
Option Explicit On
Option Strict On

Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Numerics

Namespace FiborialVB
    ' Static Class (All Members in a Module are Static/Shared)
    Module StaticFiborial
        ' Static Field
        Dim className As String
        ' Static Constructor        
        Sub New()
            className = "Static Constructor"
            Console.WriteLine(className)
        End Sub
        ' Static Method - Factorial Recursive
        Public Function FactorialR(ByVal n As Integer) As BigInteger
            If n = 1 Then
                Return 1
            Else
                Return n * FactorialR(n - 1)
            End If
        End Function
        ' Static Method - Factorial Imperative
        Public Function FactorialI(ByVal n As Integer) As BigInteger
            Dim res As BigInteger = 1
            For i = n To 1 Step -1
                res *= i
            Next            
            Return res
        End Function
        ' Static Method - Fibonacci Recursive
        Public Function FibonacciR(ByVal n As Integer) As Long
            If n < 2 Then
                Return 1
            Else
                Return FibonacciR(n - 1) + FibonacciR(n - 2)
            End If
        End Function
        ' Static Method - Fibonacci Imperative
        Public Function FibonacciI(ByVal n As Integer) As Long
            Dim i As Integer = 2
            Dim pre As Long = 1, cur As Long = 1
            Dim tmp As Long = 0
            While i <= n
                tmp = cur + pre
                pre = cur
                cur = tmp
                i += 1
            End While
            Return cur
        End Function
        ' Static Method - Benchmarking Algorithms
        Public Sub BenchmarkAlgorithm(ByVal algorithm As Integer,
                                      ByVal values As List(Of Integer))
            Dim timer As New Stopwatch()
            Dim i As Integer, facTimeResult As BigInteger,
                fibTimeResult As Long, testValue As Integer
            ' "Case/Switch" Flow Constrol Statement
            Select Case algorithm
                Case 1
                    Console.WriteLine(ControlChars.CrLf & "Factorial Imperative:")
                    ' "For" Loop Statement
                    For i = 0 To values.Count - 1 Step 1
                        testValue = values(i)
                        ' Taking Time
                        timer.Start()
                        facTimeResult = FactorialI(testValue)
                        timer.Stop()
                        ' Getting Time
                        Console.WriteLine(" ({0}) = {1}", testValue, timer.Elapsed)
                    Next
                Case 2
                    Console.WriteLine(ControlChars.CrLf & "Factorial 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 += 1
                    End While
                Case 3
                    Console.WriteLine(ControlChars.CrLf & "Fibonacci 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 += 1
                    Loop While i < values.Count
                Case 4
                    Console.WriteLine(ControlChars.CrLf & "Fibonacci Recursive:")
                    ' "For Each" Loop Statement
                    For Each item As Integer In values
                        testValue = item
                        ' Taking Time
                        timer.Start()
                        fibTimeResult = FibonacciR(testValue)
                        timer.Stop()
                        ' Getting Time
                        Console.WriteLine(" ({0}) = {1}", testValue, timer.Elapsed)
                    Next
                Case Else
                    Console.WriteLine("DONG!")
            End Select
        End Sub
    End Module

    ' Instance Class
    Public Class InstanceFiborial
        ' Instance Field
        Dim className As String
        ' Instance Constructor
        Sub New()
            Me.className = "Instance Constructor"
            Console.WriteLine(className)
        End Sub
        ' Instance Method - Factorial Recursive
        Public Function FactorialR(ByVal n As Integer) As BigInteger
            ' Calling Static Method
            Return StaticFiborial.FactorialR(n)
        End Function
        ' Instance Method - Factorial Imperative
        Public Function FactorialI(ByVal n As Integer) As BigInteger
            ' Calling Static Method
            Return StaticFiborial.FactorialI(n)
        End Function
        ' Instance Method - Fibonacci Recursive
        Public Function FibonacciR(ByVal n As Integer) As Long
            ' Calling Static Method
            Return StaticFiborial.FibonacciR(n)
        End Function
        ' Instance Method - Fibonacci Imperative
        Public Function FibonacciI(ByVal n As Integer) As Long
            ' Calling Static Method
            Return StaticFiborial.FibonacciI(n)
        End Function
    End Class

    ' Console Program  
    Friend Module Program
        Public Sub Main()

            Console.WriteLine(ControlChars.CrLf & "Static Class")
            ' Calling Static Class and Methods
            ' 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(ControlChars.CrLf & "Instance Class")
            ' Calling Instance Class and Methods 
            ' Need to instantiate before using. Calling method from instantiated object
            Dim ff As 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 a (generic) list of integer values to test
            ' From 5 to 50 by 5
            Dim values As New List(Of Integer)
            For i = 5 To 50 Step 5
                values.Add(i)
            Next
            ' 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()
        End Sub
    End Module

End Namespace

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

Namespace FiborialSeries

    Module Fiborial
        ' Using a StringBuilder as a list of string elements
        Function GetFactorialSeries(ByVal n As Integer) As String
            ' Create the String that will hold the list
            Dim series As New StringBuilder()
            ' We begin by concatenating the number you want to calculate
            ' in the following format: "!# ="
            series.Append("!")
            series.Append(n)
            series.Append(" = ")
            ' We iterate backwards through the elements of the series
            For i = n To 1 Step -1
                ' and append it to the list
                series.Append(i)
                If i > 1 Then
                    series.Append(" * ")
                Else
                    series.Append(" = ")
                End If
            Next
            ' 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()
        End Function

        ' Using a StringBuilder as a list of string elements
        Function GetFibonnaciSeries(ByVal n As Integer) As String
            ' Create the String that will hold the list
            Dim series As New StringBuilder()
            ' We begin by concatenating the first 3 values which
            ' are always constant
            series.Append("0, 1, 1")
            ' Then we calculate the Fibonacci of each element
            ' and add append it to the list
            For i = 2 To n Step 1
                If i < n Then
                    series.Append(", ")
                Else
                    series.Append(" = ")
                End If
                series.Append(Fibonacci(i))
            Next
            ' return the list as a string
            Return series.ToString()
        End Function

        Function Factorial(ByVal n As Integer) As BigInteger
            If n = 1 Then
                Return 1
            Else
                Return n * Factorial(n - 1)
            End If
        End Function

        Function Fibonacci(ByVal n As Integer) As Long
            If n < 2 Then
                Return 1
            Else
                Return Fibonacci(n - 1) + Fibonacci(n - 2)
            End If
        End Function
    End Module

    Module Program
        Sub Main()
            ' 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))
        End Sub
    End Module

End Namespace

And the Output is:

















Mixing Instance and Static/Shared 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, you cannot do that if instead of a Class you used a Module since a Module in VB.NET is like a Static Class in C#, and remember that a Static Class has the following characteristics:
  • They only contain static members.
  • They cannot be instantiated.
  • They are sealed.
  • They cannot contain Instance Constructors

Namespace FiborialExtrasVb2

    ' Instance Class
    Class Fiborial
        ' Instance Field
        Private _instanceCount As Integer
        ' Static/Shared Field
        Private Shared _staticCount As Integer
        ' Instance Read-Only Property
        ' Within instance members, you can always use  
        ' the "Me" reference pointer to access your (instance) members.
        Public ReadOnly Property InstanceCount() As Integer
            Get
                Return Me._instanceCount
            End Get
        End Property
        ' Static/Shared Read-Only Property
        ' Remeber that Properties are Methods to the CLR, so, you can also
        ' define static/shared properties for static/shared fields. 
        ' As with Static/Shared Methods, you cannot reference your class members
        ' with the "Me" reference pointer since static/shared members are not
        ' instantiated.
        Public Shared ReadOnly Property StaticCount() As Integer
            Get
                Return _staticCount
            End Get
        End Property
        ' Instance Constructor
        Public Sub New()
            Me._instanceCount = 0
            Console.WriteLine(ControlChars.CrLf & "Instance Constructor {0}",
                              Me._instanceCount)
        End Sub
        ' Static/Shared Constructor
        Shared Sub New()
            _staticCount = 0
            Console.WriteLine(ControlChars.CrLf & "Static/Shared Constructor {0}",
                              _staticCount)
        End Sub
        ' Instance Method
        Public Sub Factorial(ByVal n As Integer)
            Me._instanceCount += 1
            Console.WriteLine(ControlChars.CrLf & "Factorial({0})", n)
        End Sub
        ' Static/Shared Method
        Public Shared Sub Fibonacci(ByVal n As Integer)
            _staticCount += 1
            Console.WriteLine(ControlChars.CrLf & "Fibonacci({0})", n)
        End Sub
    End Class

    Module Program
        Sub Main()
            ' Calling Static/Shared Constructor and Methods
            ' No need to instantiate
            Fiborial.Fibonacci(5)

            ' Calling Instance Constructor and Methods
            ' Instance required
            Dim fib As New Fiborial()
            fib.Factorial(5)

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

            ' Calling Instance Constructor and Methods
            ' for a second object
            Dim fib2 As New Fiborial()
            fib2.Factorial(5)

            Console.WriteLine()
            ' Calling Static/Shared 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)
        End Sub
    End Module

End Namespace

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 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 "tried" to say, lets have a look at the following code and the output we get.

Imports System.Diagnostics
Imports System.Numerics

Namespace FiborialExtrasCs3
    Module Program
        Sub Main()
            Dim timer As New Stopwatch()
            Dim facIntResult As System.Int64 = 0
            Dim facDblResult As System.Double = 0
            Dim facBigResult As System.Numerics.BigInteger = 0

            Console.WriteLine(ControlChars.CrLf & "Factorial using Int64")
            ' Benchmark Factorial using Int64
            ' Overflow Exception!!!
            Try
                For i = 5 To 50 Step 5
                    timer.Start()
                    facIntResult = FactorialInt64(i)
                    timer.Stop()
                    Console.WriteLine(" ({0}) = {1} : {2}", i, timer.Elapsed, facIntResult)
                Next
            Catch ex As OverflowException
                ' yummy ^_^
                Console.WriteLine(" Oops! {0} ", ex.Message)
            End Try
            Console.WriteLine(ControlChars.CrLf & "Factorial using Double")
            ' Benchmark Factorial using Double
            For i = 5 To 50 Step 5
                timer.Start()
                facDblResult = FactorialDouble(i)
                timer.Stop()
                Console.WriteLine(" ({0}) = {1} : {2}", i, timer.Elapsed, facDblResult)
            Next
            Console.WriteLine(ControlChars.CrLf & "Factorial using BigInteger")
            ' Benchmark Factorial using BigInteger
            For i = 5 To 50 Step 5
                timer.Start()
                facBigResult = FactorialBigInteger(i)
                timer.Stop()
                Console.WriteLine(" ({0}) = {1} : {2}", i, timer.Elapsed, facBigResult)
            Next
        End Sub
        'Long Factorial 
        Public Function FactorialInt64(ByVal n As Integer) As Int64
            If n = 1 Then
                Return 1
            Else
                Return n * FactorialInt64(n - 1)
            End If
        End Function
        ' Double Factorial 
        Public Function FactorialDouble(ByVal n As Integer) As Double
            If n = 1 Then
                Return 1
            Else
                Return n * FactorialDouble(n - 1)
            End If
        End Function
        ' BigInteger Factorial 
        Public Function FactorialBigInteger(ByVal n As Integer) As BigInteger
            If n = 1 Then
                Return 1
            Else
                Return n * FactorialBigInteger(n - 1)
            End If
        End Function
    End Module
End Namespace

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

And the Output is: