Course of Raku / Essentials / Control flow essentials / Loops / Exercises / Fibonacci numbers
Solution: Fibonacci numbers
The following algorithm defines Fibonacci numbers.
- F0 = 0, F0 = 1
- Fn = Fn-1 + Fn-2
Code
The code implements the algorithm literally. 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
4181Remember this task as we will return to it in the future to get another exciting solution with Raku sequences.
Course navigation
← Fibonacci numbers | Echo until enough →
Translations of this page: English • Deutsch • Español • Italiano • Latviešu • Nederlands • Български • Русский • Українська