Friday, February 10, 2012

Factorial and Fibonacci in Zonnon



Here below a little program in Zonnon 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 Zonnon *)

(* Module (Static Class) *)
module StaticFiborial;
import 
  System.Numerics.BigInteger as BigInteger, 
  System.Diagnostics.Stopwatch as Stopwatch;
(* Static Field *)
var {private} className: string;

  (* Static Method - Factorial Recursive *)
  procedure {public} factorialR(n: integer): BigInteger;
  begin
  if n < 1 then
    return BigInteger.One;
  else
    return BigInteger(n) * BigInteger(factorialR(n - 1));
  end;   
  end factorialR;

  (* Static Method - Factorial Imperative *)
  procedure {public} factorialI(n: integer): BigInteger;
  var i: integer;
    res: BigInteger;
  begin 
    res := BigInteger.One;
    for i := n to 1 by -1 do 
      res := res * BigInteger(i);
    end;    
    return res;
  end factorialI;

  (* Static Method - Fibonacci Recursive *)
  procedure {public} fibonacciR(n: integer): integer{64};
  begin
    if n < 2 then
      return 1;
    else
      return fibonacciR(n - 1) + fibonacciR(n - 2);
    end;
  end fibonacciR;

  (* Static Method - Fibonacci Imperative *)
  procedure {public} fibonacciI(n: integer): integer{64};
  var i, pre, cur, tmp: integer{64};
  begin
    pre := 1;
    cur := 1;
    tmp := 0;
    for i := 2 to n do
      tmp := cur + pre;    
      pre := cur;    
      cur := tmp; 
    end; 
    return cur;
  end fibonacciI;  

  (* Static Method - Benchmarking Algorithms *)
  procedure {public} benchmarkAlgorithm(algorithm: integer; var values: array * of integer);
  var timer: Stopwatch;
    testValue: integer;
    facTimeResult: BigInteger;
    i, fibTimeResult: integer{64};
  begin
    timer := new Stopwatch(); 
    i := 0;   
    testValue := 0;   
    facTimeResult := BigInteger.Zero;
    fibTimeResult := 0;  
    (* "Switch" Flow Control Statement *)  
    case algorithm of    
    1:         
      writeln("Factorial Imperative:");
      (* "For" Loop Statement *)
      for i := 0 to len(values)-1 do
        testValue := values[i];
        (* Taking Time *)
        timer.Start;
        facTimeResult := factorialI(testValue);
        timer.Stop;
        (* Getting Time *)
        writeln(" (" + string(testValue) + ") = {" + string(timer.Elapsed) + "}");
      end;      
    | 2:
      writeln("Factorial Recursive:");
      (* "While" Loop Statement *)      
      while i < len(values) do
        testValue := values[i];
        (* Taking Time *)
        timer.Start;
        facTimeResult := factorialR(testValue);
        timer.Stop;
        (* Getting Time *)
        writeln(" (" + string(testValue) + ") = {" + string(timer.Elapsed) + "}");
        i := i + 1;
      end;
    | 3:  
      writeln("Fibonacci Imperative:");
      (* "Repeat" Loop Statement *)
      repeat
        testValue := values[i];
        (* Taking Time *)
        timer.Start;
        fibTimeResult := fibonacciI(testValue);
        timer.Stop;
        (* Getting Time *)
        writeln(" (" + string(testValue) + ") = {" + string(timer.Elapsed) + "}");
        i := i + 1;
        until i = len(values);
    | 4:  
      writeln("Fibonacci Recursive:");
      (* "Loop" Loop Statement *)
      loop
        testValue := values[i];
        (* Taking Time *)
        timer.Start;
        fibTimeResult := fibonacciR(testValue);
        timer.Stop;
        (* Getting Time *)
        writeln(" (" + string(testValue) + ") = {" + string(timer.Elapsed) + "}");
        i := i + 1;
        if i = len(values) then exit end;
        end;
    else
      (* This code will never be reached. 
      So, I'm "using" fibTimeResult & facTimeResult to avoid compile error:
      Zonnon Compiler, Version 1.2.8.0    
      The variable 'fibTimeResult' is assigned but its value is never used.
      The variable 'facTimeResult' is assigned but its value is never used.*)
      writeln(fibTimeResult);      
      writeln(string(facTimeResult)); (* BigInteger not implicitly converted*)
      writeln("DONG!");  
    end;
  end benchmarkAlgorithm;

  (* funny work around for static init code *)
  procedure {public} init;
  begin  
    (* pass *)
  end init;

(* Contructor | Initializer *)  
begin
  className := "Static Constructor";
  writeln(className);
end StaticFiborial.

(* Instance Class *)
object {ref, public} InstanceFiborial;
import System.Numerics.BigInteger as BigInteger,
  StaticFiborial;
(* Instance Field *)
var {private} className: string;

  (* Instance Method - Factorial Recursive *)
  procedure {public} factorialR(n: integer): BigInteger;
  begin
    (* Calling Static Method *)
    return StaticFiborial.factorialR(n);
  end factorialR;

  (* Instance Method - Factorial Imperative *)
  procedure {public} factorialI(n: integer): BigInteger;
  begin 
    (* Calling Static Method *)
    return StaticFiborial.factorialI(n);
  end factorialI;

  (* Instance Method - Fibonacci Recursive *)
  procedure {public} fibonacciR(n: integer): integer{64};
  begin
    (* Calling Static Method *)
    return StaticFiborial.fibonacciR(n);
  end fibonacciR;

  (* Instance Method - Fibonacci Imperative *)
  procedure {public} fibonacciI(n: integer): integer{64};
  begin
    return StaticFiborial.fibonacciI(n);
  end fibonacciI;
  
(* Instance Contructor | Initializer *)  
begin
  self.className := "Instance Constructor";
  writeln(self.className);
end InstanceFiborial.

(* Console Program *)
module Main;
import StaticFiborial, InstanceFiborial;
const N = 10;
type TestArray = array N of integer;
var i,j: integer;
  ff: InstanceFiborial; 
  values: TestArray;
begin
  writeln;
  writeln("Static Class");  
  (* Calling Static Class and Methods 
  No instantiation needed. Calling method directly from the class *)
  (* calling StaticFiborial.init to execute the static constructor code 
  otherwise the string that is being printed there will appear the first
  time a static method is called. In this case will appear like: 
  FacImp(5) =Static Constructor\n120 *)
  StaticFiborial.init;
  writeln("FacImp(5) =", string(StaticFiborial.factorialI(5)));
  writeln("FacRec(5) =", string(StaticFiborial.factorialR(5)));  
  writeln("FibImp(11)=", string(StaticFiborial.fibonacciI(11)));
  writeln("FibRec(11)=", string(StaticFiborial.fibonacciR(11)));  

  writeln;  
  writeln("Instance Class");
  (* Calling Instance Class and Methods         
  Need to instantiate before using. Calling method from instantiated object *)
  ff := new InstanceFiborial();
  writeln("FacImp(5) =", string(ff.factorialI(5)));
  writeln("FacRec(5) =", string(ff.factorialR(5)));  
  writeln("FibImp(11)=", string(ff.fibonacciI(11)));
  writeln("FibRec(11)=", string(ff.fibonacciR(11)));  
  writeln;

  (* Create a list of integer values to test    
  From 5 to 50 by 5 *)
  j := 0;
  (*for i := 5 to 50 by 5 do *)
  for i := 5 to 50 by 5 do
    values[j] := i;
    j := j + 1;
  end; 

  (* Benchmarking Fibonacci *)
  (* 1 = Factorial Imperative *)
  StaticFiborial.benchmarkAlgorithm(1, values);
  writeln;
  (* 2 = Factorial Recursive *)
  StaticFiborial.benchmarkAlgorithm(2, values);
  writeln;
        
  (* Benchmarking Factorial *)
  (* 3 = Fibonacci Imperative *)
  StaticFiborial.benchmarkAlgorithm(3, values);
  writeln;
  (* 4 = Fibonacci Recursive *)
  StaticFiborial.benchmarkAlgorithm(4, values);
  writeln;

  (* Stop and exit *)
  writeln("Press any key to exit...");
  readln();  
end Main.

And the Output is:





Printing the Factorial and Fibonacci Series
  
module Main;
import
  System.Numerics.BigInteger as BigInteger, 
  System.Text.StringBuilder as StringBuilder;

  (* Using a StringBuilder as a list of string elements *)
  procedure {public} GetFactorialSeries(n: integer): string;
  var i: integer;
    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 := n to 1 by -1 do
      (* and append it to the list *)
      series.Append(i);  
      if i > 1 then
        series.Append(" * ");  
      else   
        series.Append(" = ");   
    end;
    end;  
    (* Get the result from the Factorial Method *)
    (* and append it to the end of the list *)
    series.Append(string(Factorial(n)));
    (* return the list as a string *)
    return string(series);
  end GetFactorialSeries;

  (* Using a StringBuilder as a list of string elements *)
  procedure {public} GetFibonnaciSeries(n: integer): string;
  var i: integer;
    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 := 2 to n do 
      if i < n then
        series.Append(", ");  
      else  
        series.Append(" = ");  
      end;
      series.Append(string(Fibonacci(i)));  
    end;
    (* return the list as a string *)
    return string(series);
  end GetFibonnaciSeries;
  
  procedure {private} Factorial(n: integer): BigInteger;
  begin
    if n < 1 then
      return BigInteger.One;
    else
      return BigInteger(n) * BigInteger(Factorial(n - 1));
    end;   
  end Factorial;
  
  procedure {private} Fibonacci(n: integer): integer{64};
  begin
    if n < 2 then
      return 1;
    else
      return Fibonacci(n - 1) + Fibonacci(n - 2);
    end;
  end Fibonacci;
    
begin
  writeln;
  (* Printing Factorial Series *)
  writeln();  
  writeln(GetFactorialSeries(5));  
  writeln(GetFactorialSeries(7));  
  writeln(GetFactorialSeries(9));  
  writeln(GetFactorialSeries(11));  
  writeln(GetFactorialSeries(40));  
  (* Printing Fibonacci Series *)
  writeln();  
  writeln(GetFibonnaciSeries(5));  
  writeln(GetFibonnaciSeries(7));  
  writeln(GetFibonnaciSeries(9));  
  writeln(GetFibonnaciSeries(11));  
  writeln(GetFibonnaciSeries(40));  
  
end Main.

And the Output is:





















Mixing Instance and Static Members in the same Class

Normally, instance classes can contain both, instance and static members such as: fields, getters, constructors/initializers, methods, etc. However, Zonnon doesn't support mixing both of them on the Module or Object unit types.

 In the following code I had to create one Module and one Object to workaround this limitation.
 
(* Module (Static Class) 
  You cannot declare a variable of type ModuleName 
  If you try to do that you get a: 
  "'ModuleName' does not denote a type as expected."
*) 
module StaticFiborial;
(* Static Field *)
var {private} staticCount: integer;
  
  (* Static Read-Only Getter 
  You cannot reference your class members with the "self" 
  reference pointer since static members are not instantiated. *)
  procedure {public} StaticCount(): integer;
  begin
    return staticCount;
  end StaticCount;  
  
  (* Static Method *)
  procedure {public} Fibonacci(n: integer);
  begin
    staticCount := staticCount + 1;
    writeln;
    writeln("Fibonacci(" + string(n) + ")");
  end Fibonacci;
  
(* Static Constructor | Initializer *)  
begin
  staticCount := 0; 
  writeln("Static Constructor", staticCount:2);
end StaticFiborial.

(* Object (Instance Class) 
  You cannot try to call a method of ObjectName without an instance.
  If you try to do that you get a:
  "Cannot access to a member of 'ObjectName' 
  because it is object but not an instance of object" *)
object {ref, public} InstanceFiborial;
(* Instance Field *)
var {private} instanceCount: integer;

  (* Instance Read-Only Getter
  Within instance members, you can always use    
  the "self" reference pointer to access your (instance) members. *) 
  procedure {public} InstanceCount(): integer;
  begin
    return self.instanceCount;
  end InstanceCount;

  (* Instance Method *)
  procedure {public} Factorial(n: integer);
  begin
    self.instanceCount := self.instanceCount + 1;
    writeln;
    writeln("Factorial(" + string(n) + ")");
  end Factorial;
  
(* Instance Contructor | Initializer *)  
begin
  self.instanceCount := 0; 
  writeln("Instance Constructor", self.instanceCount:2);
end InstanceFiborial.

module Main;
import StaticFiborial, InstanceFiborial;
var fib, fib2: InstanceFiborial;  
begin  
  writeln;
  (* Calling Static Constructor and Methods 
  No need to instantiate *)  
  StaticFiborial.Fibonacci(5);

  (* Calling Instance Constructor and Methods  
  instance required *)
  fib := new InstanceFiborial();
  fib.Factorial(5);

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

  (* Calling Instance Constructor and Methods  
  for a second object *)
  fib2 := new InstanceFiborial();  
  fib2.Factorial(5);  

  writeln;
  (* Calling Static Getter *)
  writeln("Static Count =", StaticFiborial.StaticCount:2);  
  (* Calling Instance Getter of object 1 and 2 *)
  writeln("Instance 1 Count =", fib.InstanceCount:2);  
  writeln("Instance 2 Count =", fib2.InstanceCount:2);  

end Main.

And the Output is:






















Factorial using System.Int64/integer{64}, System.Double/real{64}, 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.

  
module Main;
import System.Numerics.BigInteger as BigInteger, 
  System.Diagnostics.Stopwatch as Stopwatch;
var 
  timer: Stopwatch;
  facIntResult: integer{64};
  facDblResult: real{64};
  facBigResult: BigInteger;
  i: integer;  
  
  (* Long Factorial *)
  procedure FactorialInt64(n: integer): integer{64}; 
  begin
    if n = 1 then
      return 1{64};
    else  
      return n * FactorialInt64(n - 1);  
    end;
  end FactorialInt64;

  (* Double Factorial *)
  procedure FactorialDouble(n: integer): real{64};
  begin
    if n = 1 then
      return 1.0{64};  
    else  
      return real(n) * FactorialDouble(n - 1);
    end;
  end FactorialDouble;
  
  (* BigInteger Factorial *)
  procedure FactorialBigInteger(n: integer): BigInteger;
  begin
    if n = 1 then
      return BigInteger.One;  
    else  
      return BigInteger(n) * BigInteger(FactorialBigInteger(n - 1));  
    end;
  end FactorialBigInteger;
  
begin
  timer := new Stopwatch();  
  facIntResult := 0{64};
  facDblResult := 0.0{64};  
  facBigResult := BigInteger.Zero;  
  
  writeln;
  writeln("Factorial using Int64");  
  (* Benchmark Factorial using Int64 *)
  (* Overflow Exception!!! *)
  do
    for i:= 5 to 50 by 5 do    
      timer.Start;
      facIntResult := FactorialInt64(i);
      timer.Stop;
      writeln(" (" + string(i) + ") = " + string(timer.Elapsed) + " : " 
     + string(facIntResult));
    end;  
  on exception do
    (* built-in function reason doesn't work:
 Compile Error: Entity 'reason' is not declared*)
    writeln("Oops!","OverflowException");
  on termination do
    writeln("Oops!","Exception Termination");
  end;

  writeln;
  writeln("Factorial using Double");  
  (* Benchmark Factorial using Double *)
  for i:= 5 to 50 by 5 do    
    timer.Start;
    facDblResult := FactorialDouble(i);
    timer.Stop;
    writeln(" (" + string(i) + ") = " + string(timer.Elapsed) + " : " 
   + string(facDblResult));
  end;
  
  writeln;
  writeln("Factorial using BigInteger");  
  (* Benchmark Factorial using BigInteger *)
  for i:= 5 to 50 by 5 do    
    timer.Start;
    facBigResult := FactorialBigInteger(i);
    timer.Stop;
    writeln(" (" + string(i) + ") = " + string(timer.Elapsed) + " : " 
   + string(facBigResult));
  end;
end Main.

And the Output is:

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

No comments:

Post a Comment