Course of Raku / Addendum 🆕 / Working with data / Numbers and mathematics / Exercises / Digital root

Solution: Digital root

Here is a possible solution to the task.

Code

my $n = 987654;

while $n >= 10 {
    $n = [+] $n.comb;
}

say $n;

🦋 You can find the source code in the file digital-root.raku.

Output

3

Comments

  1. $n.comb splits the number into its individual digit characters; [+] adds them, numifying the strings automatically.

  2. The loop repeats while the result still has more than one digit, so it stops as soon as $n drops below 10.

Course navigation

Digital root   |   Collatz steps