Page 1 of 1

Calculate Fibonacci Sequence Rate Topic: -----

#1 nofear217  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 14
  • View blog
  • Posts: 323
  • Joined: 08-November 07

Posted 25 July 2008 - 08:43 AM

My last tutorial calculated prime number in a range of values, now I'd like to demonstrate how to calculate a set number of values in the Fibonacci sequence. For those of you familiar with Pascal's Triangle, the addition of the short diagonals of Pascal's Triangle are the Fibonacci sequence. It can be calculated as follows:

First I will begin with the actual function that will calculate the array of numbers:

    Private Function CalcFibonacci(ByVal limit As Integer) As Integer()

        Dim _limit As Integer = (limit - 1)
        Dim result(_limit) As Integer
        Dim prevOne, prevTwo, total As Integer

        prevOne = 1
        prevTwo = 1

        For i = 0 To _limit

            If i = 0 Then
                total = 0
                result(i) = total
            ElseIf i = 1 Or i = 2 Then
                total = 1
                result(i) = total
            ElseIf i > 2 Then
                total = prevOne + prevTwo
                prevTwo = prevOne
                prevOne = total
                result(i) = total
            End If

        Next

        Return result

    End Function



As you can see it does return an array with the total number of values passed in using the limit. It then declares a new array result, dimensioning it with a size 1 less than the total number of values (because arrays are of course 0 based). I then set the two previous values to 1 as that is where we will begin to actually do the calculations since the first three values in the Fibonacci sequence are 0, 1, 1....Then I basically just start at the third value and start adding prevOne and prevTwo, then setting prevTwo = prevOne and prevOne to the current total. I then add the total into the array at the specified position. The loop will execute until we reach the limit and then return the array of values.

For a simple example of how to call this function, I used two text boxes (one for the limit and the other for the sequence):
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

        Dim number As Integer
        txtFibResults.Text = ""

        number = CType(txtFibLimit.Text, Integer)
        Dim result() As Integer = CalcFibonacci(number)

        For Each num In result
            txtFibResults.Text += num.ToString() + vbCrLf
        Next

    End Sub



And that is that...if you have any questions, feel free to reply or send me a message.

This post has been edited by nofear217: 25 July 2008 - 11:35 AM


Is This A Good Question/Topic? 0
  • +

Page 1 of 1