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:

No comments:

Post a Comment