OFFSET
0,4
COMMENTS
One way to calculate the Fibonacci numbers recursively is to use:
F(0) = 0, F(1) = 1, F(2) = 1,
F(n) = F((n + 1)/2)^2 + F((n - 1)/2)^2 for odd n,
F(n) = F(n/2) * (F(n/2 - 1) + F(n/2 + 1)) for even n.
Proof: It is known that F(i) * F(j) + F(i + 1) * F(j + 1) = F(i + j + 1) (see formula section of A000045).
For even n, let i = n/2 and j = n/2 - 1, for odd n, let i = j = (n + 1)/2.
This table gives the number of evaluations of F for calculating F(n). It is assumed that values of F which have been previously calculated are available; looking up a previously calculated value counts as a function evaluation.
a(0) = 1, a(1) = 1, a(2) = 1,
if (a(n)) has not been previously calculated then
a(n) = a((n + 1)/2) + a((n - 1)/2) + 1, n odd,
a(n) = a(n/2) + a(n/2 - 1) + a(n/2 + 1) + 1, n even,
else
a(n) = 1.
Conjecture: a(n) is O(log n).
LINKS
Thomas König, Table of n, a(n) for n = 0..10000
Thomas König, Calculation of Fibonacci numbers, Fortran program including operation counts.
EXAMPLE
Calculation of F(15) = 15:
Level of recursion is marked with indentation and "level", so calculating F(15) (level 1) calls F(8) (level 2), which calls F(5) (level 3) etc... until a cached value is reached.
F(15) level 1
F(8) level 2
F(5) level 3
F(3) level 4
F(2) level 5 cached
F(1) level 5 cached
F(2) level 4 cached
F(4) level 3
F(3) level 4 cached
F(2) level 4 cached
F(1) level 4 cached
F(3) level 3 cached
F(7) level 2
F(4) level 3 cached
F(3) level 3 cached
PROG
(Fortran) program main
implicit none
integer, parameter :: pmax = 100000
integer :: r, n
logical, dimension(0:pmax) :: cache
do n=0, pmax
cache (0:2) = .true.
cache (3:pmax) = .false.
r = a(n)
write (*, fmt="(I0, ', ')", advance="no") r
end do
write (*, fmt="()")
contains
recursive function a (n) result(r)
integer, intent(in) :: n
integer :: r
if (cache(n)) then
r = 1
return
else if (mod(n, 2) == 1) then
r = a ((n+1)/2) + a ((n-1)/2) + 1
else
r = a(n/2+1) + a (n/2) + a(n/2-1) + 1
end if
cache (n) = .true.
end function a
end program main
CROSSREFS
KEYWORD
AUTHOR
Thomas König, Jan 11 2020
STATUS
approved