Imports System
Module SumFibonacciRangeModule
' Example: left = 2, right = 8
' Explanation: F(2) + F(3) + F(4) + F(5) + F(6) + F(7) + F(8) = 1 + 2 + 3 + 5 + 8 + 13 + 21 = 53
' Function to compute Fibonacci numbers up to n
Function Fibonacci(n As Integer) As ULong
If n = 0 Then
Return 0
ElseIf n = 1 Then
Return 1
End If
Dim prev As ULong = 0
Dim curr As ULong = 1
For i As Integer = 2 To n
Dim nextVal As ULong = prev + curr
prev = curr
curr = nextVal
Next
Return curr
End Function
' Function to calculate sum of Fibonacci numbers from index L to R (inclusive)
Function SumFibonacciRange(L As Integer, R As Integer) As ULong
' If the range is invalid (e.g., L > R), return 0
If L > R Then
Return 0
End If
'
' Mathematical identity:
' Sum(F_L + F_(L+1) + ... + F_R) = F_(R+2) - F_(L+1)
'
' Explanation:
' - The sum of the first n Fibonacci numbers is F_(n+2) - 1.
' - So, the sum from F_L to F_R can be derived by subtracting:
' (sum of first R terms) - (sum of first (L-1) terms)
' = (F_(R+2) - 1) - (F_(L+1) - 1)
' = F_(R+2) - F_(L+1)
'
Return Fibonacci(R + 2) - Fibonacci(L + 1)
End Function
Sub Main()
Dim left As Integer = 2
Dim right As Integer = 8
Dim result As ULong = SumFibonacciRange(left, right)
Console.WriteLine("Sum of Fibonacci numbers from index {0} to {1} = {2}", left, right, result)
End Sub
End Module
' run:
'
' Sum of Fibonacci numbers from index 2 to 8 = 53
'