How to resolve the algorithm Leonardo numbers step by step in the Ruby programming language
How to resolve the algorithm Leonardo numbers step by step in the Ruby programming language
Table of Contents
Problem Statement
Leonardo numbers are also known as the Leonardo series.
The Leonardo numbers are a sequence of numbers defined by:
This task will be using the 3rd equation (above) to calculate the Leonardo numbers.
Edsger W. Dijkstra used Leonardo numbers as an integral part of his smoothsort algorithm.
The first few Leonardo numbers are:
(The last task requirement will produce the Fibonacci numbers.)
Show all output here on this page.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Leonardo numbers step by step in the Ruby programming language
The code snippet is a Ruby implementation of the Leonardo sequence, a sequence of numbers defined recursively by the following rules:
- The first two terms are both 1.
- Each subsequent term is the sum of the previous two terms, plus an optional increment value.
The code defines a function called leonardo
that takes three optional parameters:
l0
: The first term of the sequence.l1
: The second term of the sequence.add
: The increment value.
The function returns an enumerator if no block is given, or it yields each term of the sequence to the block if a block is given.
The code then prints the first 25 terms of the Leonardo sequence, using the default values for the first two terms and increment value (l0=1
, l1=1
, add=1
). It then prints the first 25 terms of the sequence with the first two terms set to 0 and 1, and the increment value set to 0 (l0=0
, l1=1
, add=0
).
Here is an example of the output:
[1, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, 199, 322, 521, 843, 1364, 2207, 3571, 5778, 9349, 15127, 24476, 39603, 64079, 103682]
[0, 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]
Source code in the ruby programming language
def leonardo(l0=1, l1=1, add=1)
return to_enum(__method__,l0,l1,add) unless block_given?
loop do
yield l0
l0, l1 = l1, l0+l1+add
end
end
p leonardo.take(25)
p leonardo(0,1,0).take(25)
You may also check:How to resolve the algorithm Longest string challenge step by step in the PL/I programming language
You may also check:How to resolve the algorithm Haversine formula step by step in the C programming language
You may also check:How to resolve the algorithm Read a configuration file step by step in the Phixmonti programming language
You may also check:How to resolve the algorithm Sokoban step by step in the PicoLisp programming language
You may also check:How to resolve the algorithm Sorting algorithms/Pancake sort step by step in the C programming language