Liberty BASIC Community Forum
Special Topics and Projects >> Open Source Projects >> [RC] suggested tasks- Leonardo numbers
http://libertybasic.conforums.com/index.cgi?board=open&action=display&num=1497893280

[RC] suggested tasks- Leonardo numbers
Post by tenochtitlanuk on Jun 19th, 2017, 12:28pm

Just noticed this recently suggested task-
Quote:
The Leonardo numbers are a sequence of numbers defined by:
L(0) = 1,
L(1) = 1,
L(n) = L(n-1) + L(n-2) + 1
( it also can be shown that L(n) = 2 *Fib(n+1) -1)
The task will be using the 3rd equation (above) to calculate the Leonardo numbers.


Rosetta

A nice little task that should only take you a few minutes! But room to write an elegant function/sub and format the output.....
Re: [RC] suggested tasks- Leonardo numbers
Post by tsh73 on Jun 20th, 2017, 07:50am

Recursive solution
with memoisation (don't calculate things you already know) thing.
Code:
'[RC] Leonardo numbers
'http://rosettacode.org/wiki/Leonardo_numbers
'Recursive with memoization

dim L(100)
global addNumber

print "Leonardo numbers"
addNumber=1
L(0)=1: L(1)=1

for i = 0 to 24
    print leonard(i);" ";
next
print

print "Fibonacci numbers"
redim L(100)    'clear recorded Leonardo numbers!
addNumber=0
L(0)=0: L(1)=1

for i = 0 to 24
    print leonard(i);" ";
next
print


function leonard(n)
'memoisation check
    if L(n) then leonard=L(n): exit function
    select case n
    case 0: leonard=L(0)
    case 1: leonard=L(1)
    case else: leonard=leonard(n-1)+leonard(n-2)+addNumber
    end select
'    memoisation store
    L(n)=leonard
end function
 


EDIT if you comment up "if L(n) then" line, you'll see that memoisation trick really helps a lot ;)
Re: [RC] suggested tasks- Leonardo numbers
Post by tenochtitlanuk on Jun 20th, 2017, 1:32pm

The following is one of my versions.
The task is badly specified- as stated the relationship of Leonardo and Fibonacci terms is given wrongly..
Code:
dim store( 100)

print "Fibonacci series."
for j =0 to 25
    print right$( space$( 10) +str$( leoNum( j, 1, 1, 0)), 7);
next j

print: print "Leonardo series."
for j =0 to 25
    print right$( space$( 10) +str$( leoNum( j, 1, 1, 1)), 7);
next j

'redim store( 100)

print: print leoNum( 25, 1, 1, 1), 2 *leoNum( 25, 1, 1, 0) -1

end

function leoNum( n, L0, L1, add)   'depth, first two terms, value to add
    'redim store( 100)
    if n >100 then end
    store( 0) =L0
    store( 1) =L1

    for i =2 to n
        store( i) =store( i -2) +store( i -1) +add
    next i

    leoNum =store( n)
end function
 

Quote:
Fibonacci series.
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393
Leonardo series.
1 1 3 5 9 15 25 41 67 109 177 287 465 753 1219 1973 3193 5167 8361 13529 21891 35421 57313 92735 150049 242785
242785 242785

(sorry the wiki messes up the formatting of the output number series....)