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:


No comments:

Post a Comment