Course of Raku / Essentials / Loops / Exercises / Fibonacci numbers

Solution: Fibonacci numbers

The following algorithm defines Fibonacci numbers.

  1. F0 = 0, F0 = 1
  2. Fn = Fn-1 + Fn-2

Code

The code implements the algorithm literary. It uses a couple of variables to keep the current two Fibonacci numbers and updates them in a loop. Note that both variables get updates in a single assignment.

my $a = 0;
my $b = 1;

say $a;
for ^19 {
    ($a, $b) = $b, $a + $b;
    say $a;
}

🦋 Find the program in the file fibonacci-numbers.raku.

Output

Here is the output of the program that prints 20 first numbers.

$ raku exercises/loops/fibonacci-numbers.raku
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181

More on this subject

Remember this task as we will return to it in the future to get another exciting solution with Raku sequences.

Next exercise

💪 Echo until enough

Course navigation

Conditional checks / Ternary operator   |   Data type conversion