Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Imports System.

Numerics

Public Class FrmFibonacci

'Function for determining Odd or Even

'Using Mod Function

Function IsOddEven(ByVal input As BigInteger) As String

If input Mod 2 = 0 Then

Return $"{input} EVEN - DELA ROSA{vbCrLf}"

End If

Return $"{input} ODD - MARK ANTHONY{vbCrLf}"

End Function

'Function for checking Inputs Letters are not allowed

Function CheckInputs(ByVal n As String) As Integer

Dim r As Integer = 0

If Integer.TryParse(n, r) Then

r = CInt(n)

Else

'Return error message if the input is not a number

txtOutput.Text = $"[{n}] is not a valid number.{vbCrLf} We will return 0 by default


{vbCrLf}"

txtOutput.Text += ($"----------------------------{vbCrLf}")

End If

Return r

End Function

'We use Async for better execution

Private Async Sub btnDisplayFibonacci_Click(sender As Object, e As EventArgs) Handles


btnDisplayFibonacci.Click

Await GetResultAsync()

End Sub
'We need to run the method as a task to get Awaiter

Async Function GetResultAsync() As Task

Await Task.Run(AddressOf Display)

End Function

'Displaying the result

'Because of Asynchronous we don't want to cause trouble about threading

'So we need to invoke our UI elements that is our TextBoxes

Private Sub Display()

If Me.InvokeRequired Then 'If invocation is required

Me.Invoke(New MethodInvoker(AddressOf Display))

Else

txtOutput.Clear()

Me.Refresh()

For i As Integer = 0 To CheckInputs(txtInput.Text) 'Check input if valid, else return


a message

txtOutput.Text += $"{IsOddEven(GenerateSequenceAsync(i).Result) }" 'Our output

Next

End If

End Sub

'Generate Fibonacci sequence

'Using Recursion Algorithm

'Then we made it as Asynchronous method

'Function is F(n) = F(n-1) + F(n-2)

Async Function GenerateSequenceAsync(ByVal nTerm As Integer) As Task(Of BigInteger)

If nTerm < 2 Then Return nTerm

Return Await GenerateSequenceAsync(nTerm - 1) + Await GenerateSequenceAsync(nTerm - 2)

End Function

End Class

You might also like