Course of Raku / Essentials / Control flow essentials / Loops / Exercises / Factorial
Solution: Factorial
A factorial of N is a product of integer numbers from 1
to and including N. E.g., factorial of 4 is 1 * 2 * 3 * 4 =
24.
Code
my $n = 8;
my $f = 1;
$f *= $_ for 2..$n;
say $f;🦋 Find the program in the file factorial.raku.
Output
Run the program a few times and try different values of
$n.
$ raku exercises/loops/factorial.raku
40320Comments
This program uses the *= operator, which is a shortcut
for multiplication with the assignment: $x *= $y is
equivalent to $x = $x * $y.
You can use a ’full‘ loop instead of a postfix form:
my $n = 8;
my $f = 1;
for 2..$n -> $x {
$f *= $x;
}
say $f;We will return to this task a number of times. In this part of the course, we will also solve this problem recursively.
In the second part of the course, we will learn about the so-called
reduction operators, which make the solution trivial. Also, there will
be a way to define a custom operator ! so that you can
write $n! to compute a factorial. Finally, there will be
another chance to see an interesting solution when we’ll talk about the
where clause.
Course navigation
← Factorial | Fibonacci numbers →
Translations of this page: English • Deutsch • Español • Italiano • Latviešu • Nederlands • Български • Русский • Українська