Working with Primes and Fibonacci Sequences in Visual Basic

Introduction

Numbers: We all love them, but we all hate them. I personally love to hate them. Today, I will try to help, especially the young aspiring developer students, to play with the Fibonacci sequence and prime numbers.

Prime Numbers

https://en.wikipedia.org/wiki/Prime_number

Fibonacci

https://en.wikipedia.org/wiki/Fibonacci_number

Our Project

Start a new Visual Basic Windows Forms project and add another form to your existing project.

Design your Form 1 to resemble Figure 1:

Number1
Figure 1: First Form

Design Form 2 to resemble Figure 2:

Number2
Figure 2: Second form

The first form will cover primes, whereas the second form will cover the Fibonacci sequence

Primes: Form 1

Declare an array to hold the Prime numbers:

   Private arrPrimes(0) As Long

Initialize the Form's interface inside Form_Load

   Private Sub Form1_Load(ByVal sender As Object, _
         ByVal e As System.EventArgs) Handles Me.Load
      ReDim arrPrimes(0)
      arrPrimes(0) = 2
      ListBox1.Items.Clear()
   End Sub

Here, I redimensioned the arrPrimes array to 0, because it is the starting point. Obviously, you could have made a little sub procedure to initialize all the objects, and start another sequence, but this is just an example. I seeded the first element of the array with the number 2 because it is the first prime number and then I simply cleared the List Box.

Add the following code inside Button1's click event:

   Private Sub Button1_Click(ByVal sender As Object, _
         ByVal e As System.EventArgs) Handles Button1.Click
      Try
         Dim Value As Object
         BuildPrimeList(GetMaxNumber())

         For Each Value In arrPrimes
            ListBox1.Items.Add(Value.ToString())
         Next

         Exit Sub
      Catch ex As Exception
         MsgBox(ex.Message.ToString())
      End Try
   End Sub

Inside Button1, I declared an object variable to host the current prime number value. I called the BuildPrimes sub procedure that uses the result of the GetMaxNumber function as an argument. We will create them shortly. After I have determined the prime numbers in the sequence, I add them into the listbox. Let's create the BuildPrimes Sub now:

   Private Sub BuildPrimeList(ByVal Max As Long)

      If (Max < 3) Then Exit Sub
      Dim I As Long

      For I = 2 To Max
         If (DeterminePrime(I)) Then
            'As Long
            ReDim Preserve arrPrimes(UBound(arrPrimes) + 1)
            arrPrimes(UBound(arrPrimes)) = I
         End If
      Next

   End Sub

Okay, concentrate now! I first established whether the Max argument is less than 3. Why? Well, as I mentioned earlier in the Form_Load event, the first prime number is obviously 2, so the aim of the BuildPrimes sub is to get the next prime numbers after 2.

I started a For loop that obviously starts at 2 (again) and loops until the Max number. The Max number will be entered inside the Textbox, but you will see that only when we create the GetMaxNumber function.

Inside the loop, I first check to see if the current number in the For loop is indeed a prime number by using the DeterminePrime function (which we also will create shortly). If the current number is a prime number, I redimensioned the arrPrimes array and add it to the top of the list.

Let's create the GetMaxNumber function now:

   Private Function GetMaxNumber() As Long
      Try
         GetMaxNumber = CLng(TextBox1.Text)
         Exit Function
      Catch ex As exception
         GetMaxNumber = 0
         MessageBox.Show("Not a number")
      End Try
   End Function

This is a very basic function that simply returns the entered value inside the TextBox. Let's add the DeterminePrime function:

   Private Function DeterminePrime(ByVal lngNumber As Long)

      DeterminePrime = False
      Dim I As Long
      For I = LBound(arrPrimes) To UBound(arrPrimes)
         Application.DoEvents()

         If (lngNumber Mod arrPrimes(I) = 0) _
            Then Exit Function
         If (arrPrimes(I) >= Math.Sqrt(lngNumber)) _
            Then Exit For
      Next
      DeterminePrime = True
   End Function

This is where we calculate the next Prime number. First, I initialize the return value of this function to false. I then created a For loop that loops from the lowest entry in the arrPrimes array to the highest entry inside the arrPrimes array. Because this can very quickly eat all your memory resources, causing a potential bottle-neck, it is necessary to add the call to Application.DoEvents. Otherwise, your application will freeze.

The first calculation determines if the result of dividing lngNumber with the current number (in the loop) is 0. If the remainder of this sum is 0, the function gets exited.

The next calculation determines if the current array index is greater than or equal to the square root of lngNumber. If it is, I exit the loop and proceed to the next number in the array, which simply outputs only the next prime number.

Fibonacci: Form 2

Add the following code to your Button1's Click event:

   Private Sub Button1_Click(ByVal sender As System.Object, _
         ByVal e As System.EventArgs) Handles Button1.Click
      Dim n As Integer
      For n = 1 To 40
         ListBox1.Items.Add(fib(n))
         Application.DoEvents()
      Next
   End Sub

Here, you created a loop (1 to 40) and you add the result of the fib Function (which we will create shortly) to the ListBox. Again, note the use of Application.DoEvents here. If you do not include it, your application will get stuck until all the calculations have been completed.

Add the fib function now:

   Function fib(ByVal n)
      If n < 2 Then Return n _
         Else Return fib(n - 1) + fib(n - 2)
   End Function

The fib function makes use of an argument named n whose value gets supplied in the preceding loop inside Button1's click event. The If statement checks to see whether the value is less than 2. If it is less than 2, it returns nothing. If the value is greater than 2, it takes the sum of the current value -1 and the current value -2 by means of recursion

If you were to run your app now you will see the output in Figures 3 and 4.

Number3
Figure 3: Primes list

Number4
Figure 4: Fibonacci sequence

Conclusion

As you can see, these number sequences are not too complicated to understand and use in your programs. Until we meet again.



About the Author

Hannes DuPreez

Hannes du Preez is a Microsoft MVP for Visual Basic for the eighth consecutive year. He loves technology and loves Visual Basic. He has a lot of experience in .NET and loves to share his love, pain and musings about Visual Basic

Related Articles

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date