Generating numbers using recursion and memoization.
<?pas
// Fibonacci Sequence: Generating numbers using recursion and memoization.
var memo: array[Integer] of Integer;
// Calculates the Nth Fibonacci number recursively with memoization
function FibonacciRecursive(n: Integer): Integer;
begin
if n <= 1 then
Exit(n);
if n in memo then
Exit(memo[n]);
memo[n] := FibonacciRecursive(n - 1) + FibonacciRecursive(n - 2);
Result := memo[n];
end;
// Calculates the Nth Fibonacci number iteratively (more efficient)
function FibonacciIterative(n: Integer): Integer;
var
i: Integer;
a, b, temp: Integer;
begin
if n <= 1 then
Exit(n);
a := 0;
b := 1;
for i := 2 to n do begin
temp := a + b;
a := b;
b := temp;
end;
Result := b;
end;
// Main Execution
var n := 10;
PrintLn('<h3>Recursive Approach (with Memoization)</h3>');
PrintLn('Fibonacci(' + IntToStr(n) + ') = ' + IntToStr(FibonacciRecursive(n)));
PrintLn('<hr>');
PrintLn('<h3>Iterative Approach</h3>');
PrintLn('Fibonacci(' + IntToStr(n) + ') = ' + IntToStr(FibonacciIterative(n)));
PrintLn('<hr>');
PrintLn('<h3>Sequence Output (Iterative)</h3>');
var seq := '';
for var i := 0 to n do begin
if i > 0 then seq := seq + ', ';
seq := seq + IntToStr(FibonacciIterative(i));
end;
PrintLn(seq);
?>
<h3>Recursive Approach (with Memoization)</h3> Fibonacci(10) = 55 <hr> <h3>Iterative Approach</h3> Fibonacci(10) = 55 <hr> <h3>Sequence Output (Iterative)</h3> 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55