Here below a little program in Cobra 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 Cobra use System.Collections.Generic use System.Diagnostics use System.Numerics namespace FiborialCobra # Static Class class StaticFiborial is public shared # Static Field var __className as String # Static Constructor cue init __className = 'Static Constructor' print '[__className]' # Static Method - Factorial Recursive def factorialR(n as int) as BigInteger is public if n == 1 return BigInteger.one else return BigInteger.multiply(BigInteger(n), .factorialR(n - 1)) # Static Method - Factorial Imperative def factorialI(n as int) as BigInteger is public res as BigInteger = BigInteger.one for i as int in n:0:-1 res = BigInteger.multiply(res, BigInteger(i)) return res # Static Method - Fibonacci Recursive def fibonacciR(n as int) as int64 is public if n < 2 return 1 else return .fibonacciR(n - 1) + .fibonacciR(n - 2) # Static Method - Fibonacci Imperative def fibonacciI(n as int) as int64 is public pre as int64 = 1 cur as int64 = 1 tmp as int64 = 0 for i as int in 2:n+1 tmp = cur + pre pre = cur cur = tmp i=i # ignore compiler warning return cur # Static Method - Benchmarking Algorithms def benchmarkAlgorithm(algorithm as int, values as List<of int>) is public timer as Stopwatch = Stopwatch() i as int = 0 testValue as int = 0 facTimeResult as BigInteger = BigInteger.zero fibTimeResult as int64 = 0 facTimeResult = facTimeResult fibTimeResult = fibTimeResult # "if-elif-else" Flow Control Statement if algorithm == 1 print '\nFactorial Imperative:' # "For in range" Loop Statement for i as int in values.count testValue = values[i] # Taking Time timer.start facTimeResult = .factorialI(testValue) timer.stop # Getting Time print ' ([testValue]) = [timer.elapsed]' else if algorithm == 2 print '\nFactorial Recursive:' # "While" Loop Statement while i < values.count testValue = values[i] # Taking Time timer.start facTimeResult = .factorialR(testValue) timer.stop # Getting Time print ' ([testValue]) = [timer.elapsed]' i += 1 else if algorithm == 3 print "\nFibonacci Imperative:" # "Do-While" Loop Statement post while i < values.count testValue = values[i] # Taking Time timer.start fibTimeResult = .fibonacciI(testValue) timer.stop # Getting Time print ' ([testValue]) = [timer.elapsed]' i += 1 else if algorithm == 4 print "\nFibonacci Recursive:" # "For in List" Loop Statement for i as int in values.count testValue = values[i] # Taking Time timer.start fibTimeResult = .fibonacciR(testValue) timer.stop # Getting Time print ' ([testValue]) = [timer.elapsed]' else print 'DONG!' # Instance Class class InstanceFiborial is public # Instances Field var __className as String # Instance Constructor cue init base.init __className = "Instance Constructor" print __className # Instance Method - Factorial Recursive def factorialR(n as int) as BigInteger is public # Calling Static Method return StaticFiborial.factorialR(n) # Instance Method - Factorial Imperative def factorialI(n as int) as BigInteger is public # Calling Static Method return StaticFiborial.factorialI(n) # Instance Method - Fibonacci Recursive def fibonacciR(n as int) as int64 is public # Calling Static Method return StaticFiborial.fibonacciR(n) # Instance Method - Fibonacci Imperative def fibonacciI(n as int) as int64 is public # Calling Static Method return StaticFiborial.fibonacciI(n) # Console Program class Program is public def main is shared 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. Call method from instantiated obj 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 List of integer values to test # From 5 to 50 by 5 values as List<of int> = List<of int>() for i as int in 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.read

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**

use System.Text use System.Numerics namespace FiborialSeries # Instance Class class Fiborial is public shared # Using a StringBuilder as a list of string elements def getFactorialSeries(n as int) as String is public # 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 n:0:-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 def getFibonnaciSeries(n as int) as String is public # 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 2:n+1 if i < n series.append(', ') else series.append(' = ') series.append(.fibonacci(i)) # return the list as a string return series.toString def factorial(n as int) as BigInteger is public if n == 1 return BigInteger.one else return BigInteger.multiply(BigInteger(n), .factorial(n - 1)) def fibonacci(n as int) as int64 is public if n < 2 return 1 else return .fibonacci(n - 1) + .fibonacci(n - 2) # Console Program class Program is public def main is shared # 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.read

And the Output is:

**Mixing Instance and Static Members in the same Class**

Instance classes can contain both, instance and static members such as: fields, properties, constructors, methods, etc.

namespace FiborialExtrasCobra2 # Instance Classes can have both: static and instance members. # Instance Class class Fiborial is public # Instance Field var __instanceCount as int # Static Field var __staticCount as int is shared # Instance Read-Only Property pro instanceCount as int is public get return __instanceCount # Static Read-Only Property # Remeber that Properties are Methods to the CLR, so, # you can also define static properties for static fields. pro staticCount as int is shared, public get return __staticCount # Instance Constructor cue init base.init __instanceCount = 0 print '\nInstance Constructor [__instanceCount]' # Static Constructor cue init is shared __staticCount = 0 print '\nStatic Constructor [__staticCount]' # Instance Method def factorial(n as int) is public __instanceCount += 1 print '\nFactorial([n])' # Static Method def fibonacci(n as int) is shared, public __staticCount += 1 print '\nFibonacci([n])' # Console Program class Program is public def main is shared # 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.read

And the Output is:

**Factorial using System.Int64, System.Double/Float, 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.

use System.Diagnostics use System.Numerics namespace FiborialExtrasCobra3 class FiborialExtrasProgram shared def main timer as Stopwatch = Stopwatch() facIntResult as int64 = 0 facDblResult as float = 0 facBigResult as BigInteger = BigInteger.zero i as int = 0 print '\nFactorial using Int64' # Benchmark Factorial using Int64 for i as int in 5:55:5 timer.start facIntResult = .factorialInt64(i) timer.stop print ' ([i]) = [timer.elapsed] : [facIntResult]' print '\nFactorial using Float' # Benchmark Factorial using float for i as int in 5:55:5 timer.start facDblResult = .factorialFloat(i) timer.stop print ' ([i]) = [timer.elapsed] : [facDblResult]' print '\nFactorial using BigInteger' # Benchmark Factorial using BigInteger for i as int in 5:55:5 timer.start facBigResult = .factorialBigInteger(i) timer.stop print ' ([i]) = [timer.elapsed] : [facBigResult]' Console.read # Long Factorial def factorialInt64(n as int) as int64 if n == 1 return 1 else return n * .factorialInt64(n - 1) # float/Number Factorial def factorialFloat(n as int) as float if n == 1 return 1 else return n * .factorialFloat(n - 1) # BigInteger Factorial def factorialBigInteger(n as int) as BigInteger if n == 1 return BigInteger.one else return BigInteger.multiply(BigInteger(n), .factorialBigInteger(n - 1))

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: