program SumFibonacciRange;
{ 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: Integer): QWord;
var
prev, curr, next: QWord;
i: Integer;
begin
if n = 0 then
Fibonacci := 0
else if n = 1 then
Fibonacci := 1
else
begin
prev := 0;
curr := 1;
for i := 2 to n do
begin
next := prev + curr;
prev := curr;
curr := next;
end;
Fibonacci := curr;
end;
end;
{ Function to calculate sum of Fibonacci numbers from index L to R (inclusive) }
function SumFibonacciRange(L, R: Integer): QWord;
begin
{ If the range is invalid (e.g., L > R), return 0 }
if L > R then
SumFibonacciRange := 0
else
begin
{
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)
}
SumFibonacciRange := Fibonacci(R + 2) - Fibonacci(L + 1);
end;
end;
var
left, right: Integer;
result: QWord;
begin
left := 2;
right := 8;
result := SumFibonacciRange(left, right);
WriteLn('Sum of Fibonacci numbers from index ', left, ' to ', right, ' = ', result);
end.
(*
run:
Sum of Fibonacci numbers from index 2 to 8 = 53
*)