## Tuesday, March 8, 2011

### Factorial and Fibonacci in Boo

Here below a little program in Boo 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 Boo
namespace FiborialBoo
import System
import System.Collections.Generic
import System.Diagnostics
import System.Numerics

// Static Class
public static class StaticFiborial:
// Static Field
private className as string
// Static Constructor
def constructor():
className = "Static Constructor"
print className
// Static Method - Factorial Recursive
public def FactorialR(n as int) as BigInteger:
if n == 1:
return 1
else:
return n * FactorialR(n - 1)
// Static Method - Factorial Imperative
public def FactorialI(n as int) as BigInteger:
res as BigInteger = 1
for i as int in range(n, 1):
res *= i
return res
// Static Method - Fibonacci Recursive
public def FibonacciR(n as int) as long:
if n < 2:
return 1
else:
return FibonacciR(n - 1) + FibonacciR(n - 2)
// Static Method - Fibonacci Imperative
public def FibonacciI(n as int) as long:
pre as long = 1
cur as long = 1
tmp as long = 0
for i as int in range(2, n+1):
tmp = cur + pre
pre = cur
cur = tmp
return cur
// Static Method - Benchmarking Algorithms
public def BenchmarkAlgorithm(algorithm as int, values as List[of int]) as void:
timer as Stopwatch = Stopwatch()
i as int = 0
testValue as int = 0
facTimeResult as BigInteger = 0
fibTimeResult as long = 0

// "if-elif-else" Flow Control Statement
if algorithm == 1:
print "\nFactorial Imperative:"
// "For in range" Loop Statement
for i in range(values.Count):
testValue = values[i]
// Taking Time
timer.Start()
facTimeResult = FactorialI(testValue)
timer.Stop()
// Getting Time
print " (\${testValue}) = \${timer.Elapsed}"
elif algorithm == 2:
print "\nFactorial Recursive:"
// "While" Loop Statement
while i < len(values):
testValue = values[i]
// Taking Time
timer.Start()
facTimeResult = FactorialR(testValue)
timer.Stop()
// Getting Time
print " (\${testValue}) = \${timer.Elapsed}"
i += 1
elif algorithm == 3:
print "\nFibonacci Imperative:"
// "For in List" Loop Statement
for item as int in values:
testValue = item
// Taking Time
timer.Start()
fibTimeResult = FibonacciI(testValue)
timer.Stop()
// Getting Time
print " (\${testValue}) = \${timer.Elapsed}"
elif algorithm == 4:
print "\nFibonacci Recursive:"
// "For in List" Loop Statement
for item as int in values:
testValue = item
// Taking Time
timer.Start()
fibTimeResult = FibonacciR(testValue)
timer.Stop()
// Getting Time
print " (\${testValue}) = \${timer.Elapsed}"
else:
print "DONG!"

// Instance Class
public class InstanceFiborial:
// Instances Field
private className as string
// Instance Constructor
def constructor():
self.className = "Instance Constructor"
print self.className
// Instance Method - Factorial Recursive
public def FactorialR(n as int) as BigInteger:
// Calling Static Method
return StaticFiborial.FactorialR(n)
// Instance Method - Factorial Imperative
public def FactorialI(n as int) as BigInteger:
// Calling Static Method
return StaticFiborial.FactorialI(n)
// Instance Method - Fibonacci Recursive
public def FibonacciR(n as int) as long:
// Calling Static Method
return StaticFiborial.FibonacciR(n)
// Instance Method - Fibonacci Imperative
public def FibonacciI(n as int) as long:
// Calling Static Method
return StaticFiborial.FibonacciI(n)

public def Main(argv as (string)):
print "\nStatic Class"
// Calling Static Class and Methods
// No instantiation needed. Calling method directly from the class
print "FacImp(5) = \${StaticFiborial.FactorialI(5)}"
print "FacRec(5) = \${StaticFiborial.FactorialR(5)}"
print "FibImp(11)= \${StaticFiborial.FibonacciI(11)}"
print "FibRec(11)= \${StaticFiborial.FibonacciR(11)}"

print "\nInstance Class"
// Calling Instance Class and Methods
// Need to instantiate before using. Calling method from instantiated object
ff as InstanceFiborial = InstanceFiborial()
print "FacImp(5) = \${ff.FactorialI(5)}"
print "FacRec(5) = \${ff.FactorialR(5)}"
print "FibImp(11)= \${ff.FibonacciI(11)}"
print "FibRec(11)= \${ff.FibonacciR(11)}"

// Create a (Boo) list of values to test
// From 5 to 50 by 5
values as List[of int] = List[of int]()
for i as int in range(5,55,5):
values.Add(i)

// Benchmarking Fibonacci
// 1 = Factorial Imperative
StaticFiborial.BenchmarkAlgorithm(1, values)
// 2 = Factorial Recursive
StaticFiborial.BenchmarkAlgorithm(2, values)
// Benchmarking Factorial
// 3 = Fibonacci Imperative
StaticFiborial.BenchmarkAlgorithm(3, values)
// 4 = Fibonacci Recursive
StaticFiborial.BenchmarkAlgorithm(4, values)

// Stop and Exit
Console.ReadKey(true)
```

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

// Static Class
public static class Fiborial:
// Using a StringBuilder as a list of string elements
public def GetFactorialSeries(n as int) as string:
// Create the String that will hold the list
series as StringBuilder = StringBuilder()
// We begin by concatenating the number you want to calculate
// in the following format: "!# ="
series.Append("!")
series.Append(n)
series.Append(" = ")
// We iterate backwards through the elements of the series
for i as int in range(n, 1):
// and append it to the list
series.Append(i)
if i > 1:
series.Append(" * ")
else:
series.Append(" = ")
// Get the result from the Factorial Method
// and append it to the end of the list
series.Append(Factorial(n))
// return the list as a string
return series.ToString()

// Using a StringBuilder as a list of string elements
public def GetFibonnaciSeries(n as int) as string:
// Create the String that will hold the list
series as StringBuilder = StringBuilder()
// We begin by concatenating the first 3 values which
// are always constant
series.Append("0, 1, 1")
// Then we calculate the Fibonacci of each element
// and add append it to the list
for i as int in range(2, n+1):
if i < n:
series.Append(", ")
else:
series.Append(" = ")
series.Append(Fibonacci(i))
// return the list as a string
return series.ToString()

public def Factorial(n as int) as BigInteger:
if n == 1:
return 1
else:
return n * Factorial(n - 1)

public def Fibonacci(n as int) as long:
if n < 2:
return 1
else:
return Fibonacci(n - 1) + Fibonacci(n - 2)

public def Main(argv as (string)):
// Printing Factorial Series
print ""
print Fiborial.GetFactorialSeries(5)
print Fiborial.GetFactorialSeries(7)
print Fiborial.GetFactorialSeries(9)
print Fiborial.GetFactorialSeries(11)
print Fiborial.GetFactorialSeries(40)
// Printing Fibonacci Series
print ""
print Fiborial.GetFibonnaciSeries(5)
print Fiborial.GetFibonnaciSeries(7)
print Fiborial.GetFibonnaciSeries(9)
print Fiborial.GetFibonnaciSeries(11)
print Fiborial.GetFibonnaciSeries(40)

Console.ReadKey(true)
```

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 FiborialExtrasBoo2
import System

// 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
public class Fiborial:
// Instance Field
private instanceCount as int
// Static Field
private static staticCount as int
// Instance Read-Only Property
// Within instance members, you can always use
// the "self" reference pointer to access your (instance) members.
public InstanceCount as int:
get:
return self.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 "self" reference pointer since static members are not
// instantiated.
public static StaticCount as int:
get:
return staticCount
// Instance Constructor
public def constructor():
self.instanceCount = 0
print "\nInstance Constructor \${self.instanceCount}"
// Static Constructor
private static def constructor():
staticCount = 0
print "\nStatic Constructor \${staticCount}"
// Instance Method
public def Factorial(n as int) as void:
self.instanceCount += 1
print "\nFactorial(\${n})"
// Static Method
public static def Fibonacci(n as int) as void:
staticCount += 1
print "\nFibonacci(\${n})"

public def Main(argv as (string)):
// Calling Static Constructor and Methods
// No need to instantiate
Fiborial.Fibonacci(5)

// Calling Instance Constructor and Methods
// Instance required
fib as Fiborial = Fiborial()
fib.Factorial(5)

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

// Calling Instance Constructor and Methods
// for a second object
fib2 as Fiborial = Fiborial()
fib2.Factorial(5)

print ""
// Calling Static Property
print "Static Count = \${Fiborial.StaticCount}"
// Calling Instance Property of object 1 and 2
print "Instance 1 Count = \${fib.InstanceCount}"
print "Instance 2 Count = \${fib2.InstanceCount}"
Console.ReadKey(true)
```

And the Output is:

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

The Factorial of numbers over 20 are massive!
For instance: !40 = 815915283247897734345611269596115894272000000000!
Because of this, the previous version of this program was giving the "wrong" result
!40 = -70609262346240000 when using "long" (System.Int64) type, but it was not until I did the Fiborial version in VB.NET that I realized about this faulty code, because instead of giving me a wrong value, VB.NET, JScript.NET, Boo execution thrown an Overflow Exception when using the "Long/long" (System.Int64) type.

My first idea was to use ulong and ULong, but both failed for "big" numbers. I then used Double (double floating point) type and got no more exception/wrong result. The result of the factorial was now correct !40 = 1.1962222086548E+56, but still I wanted to show the Integer value of it, so I did some research and found that there is a new System.Numerics.BigInteger class in the .NET Framework 4.0. Adding the reference to the project and using this new class as the return type of the Factorial methods, I was able to get the result I was expecting.
!40 = 815915283247897734345611269596115894272000000000

What I also found was that using different types change the time the algorithm takes to finish:
System.Int64 < System.Double < System.Numerics.BigInteger
Almost by double!

To illustrate what I just "tried" to say, lets have a look at the following code and the output we get.

```namespace FiborialExtrasBoo3
import System
import System.Diagnostics
import System.Numerics

# Long Factorial
def FactorialInt64(n as int) as long:
if n == 1:
return 1
else:
return n * FactorialInt64(n - 1)

# Double/Number Factorial
def FactorialDouble(n as int) as double:
if n == 1:
return 1
else:
return n * FactorialDouble(n - 1)

# BigInteger Factorial
def FactorialBigInteger(n as int) as BigInteger:
if n == 1:
return 1
else:
return n * FactorialBigInteger(n - 1)

public def Main(argv as (string)):
timer as Stopwatch = Stopwatch()
facIntResult as long = 0
facDblResult as double = 0
facBigResult as BigInteger = 0
i as int = 0

print "\nFactorial using Int64"
# Benchmark Factorial using Int64
# Overflow Exception!!!
try:
for i as int in range(5,55,5):
timer.Start()
facIntResult = FactorialInt64(i)
timer.Stop()
print " (\${i}) = \${timer.Elapsed} : \${facIntResult}"
except ex as ArithmeticException:
# yummy ^_^
print "Oops! \${ex.Message} "

print "\nFactorial using Double"
# Benchmark Factorial using Double
for i as int in range(5,55,5):
timer.Start()
facDblResult = FactorialDouble(i)
timer.Stop()
print " (\${i}) = \${timer.Elapsed} : \${facDblResult}"

print "\nFactorial using BigInteger"
# Benchmark Factorial using BigInteger
for i as int in range(5,55,5):
timer.Start()
facBigResult = FactorialBigInteger(i)
timer.Stop()
print " (\${i}) = \${timer.Elapsed} : \${facBigResult}"

Console.ReadKey(true)
```

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: