recursivefunction f (n) result(res)
integer, value, intent(in) :: n
integer :: res
if (n == 0) then
res = 0elseif (n <= 2) then
res = 1elseif (mod(n,2) == 1) then
res = f((n + 1)/2)**2 + f((n - 1)/2)**2else
res = f(n/2) * (f(n/2-1) + f(n/2 + 1))
endifendifendfunction f
The function has to be marked recursive. Because it calls itself, it needs a result clause for the name of the result.
The algorithm (a bit more efficient than straight recursion) is due to https://oeis.org/A331124 .
funcfibonacci(n int)int {
if n <= 1 {
return n
}
return fibonacci(n-1) + fibonacci(n-2)
}
fib :: Int -> Intfib0 = 0fib1 = 1fib n = fib n-1 + fib n-2
(defun fibonacci (n&optional (a0) (b1) (acc ()))
(if (zerop n)
(nreverse acc)
(fibonacci (1- n) b (+ a b) (cons a acc))))
function fib(n: word): uint64;
begin
if (n in [0,1]) then
result := n
else
result := fib(n-2) + fib(n-1);
end;
recursive function f (n) result(res)
integer, value, intent(in) :: n
integer :: res
if (n == 0) then
res = 0
else if (n <= 2) then
res = 1
else
if (mod(n,2) == 1) then
res = f((n + 1)/2)**2 + f((n - 1)/2)**2
else
res = f(n/2) * (f(n/2-1) + f(n/2 + 1))
end if
end if
end function f