How to resolve the algorithm Fibonacci sequence step by step in the Octave programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Fibonacci sequence step by step in the Octave programming language

Table of Contents

Problem Statement

The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively:

Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: support for negative     n     in the solution is optional.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Fibonacci sequence step by step in the Octave programming language

Source code in the octave programming language

% recursive
function fibo = recfibo(n)
  if ( n < 2 )
    fibo = n;
  else
    fibo = recfibo(n-1) + recfibo(n-2);
  endif
endfunction

% testing
for i = 0 : 20
  printf("%d %d\n", i, recfibo(i));
endfor

% iterative
function fibo = iterfibo(n)
  if ( n < 2 )
    fibo = n;
  else
    f = zeros(2,1);
    f(1) = 0; 
    f(2) = 1;
    for i = 2 : n
      t = f(2);
      f(2) = f(1) + f(2);
      f(1) = t;
    endfor
    fibo = f(2);
  endif
endfunction

% testing
for i = 0 : 20
  printf("%d %d\n", i, iterfibo(i));
endfor

function retval = fibanalytic(n)
  retval = round(((5 .^ 0.5 + 1) / 2) .^ n / 5 .^ 0.5);
endfunction

function retval = fibtailrecursive(n, prevfib = 0, fib = 1)
  if (n == 0)
    retval = prevfib;
  else
    retval = fibtailrecursive(n - 1, fib, prevfib + fib);
  endif
endfunction

  

You may also check:How to resolve the algorithm Date manipulation step by step in the zkl programming language
You may also check:How to resolve the algorithm UTF-8 encode and decode step by step in the Haskell programming language
You may also check:How to resolve the algorithm Long multiplication step by step in the Liberty BASIC programming language
You may also check:How to resolve the algorithm System time step by step in the Nim programming language
You may also check:How to resolve the algorithm Fibonacci word step by step in the Kotlin programming language