I’ve been doing the Weekly
Challenges. The
latest
involved extracting digital roots. (Note that this ends today.)
Task 1: Digital Root
You are given a positive integer, $int.
Write a function that calculates the additive persistence of a
positive integer and also return the digital root.
Digital root is the recursive sum of all digits in a number until a single digit is obtained.
Additive persistence is the number of times you need to sum the
digits to reach a single digit.
As usual I avoided string conversions. This Raku code is the same
algorithm I used in all the other languages.
sub digitalroot($a) {
Initialise count ahd rolling value.
my $count = 0;
my $value = $a;
If the value is more than one digit:
while ($value > 9) {
Initialise a new value.
my $p = 0;
While there are digits left,
while ($value > 0) {
Add the last digit to the new value,
$p += $value % 10;
And shift the rest of them to the right.
$value = floor($value / 10);
}
Copy that into the rolling value, and increment the count. Then loop
back and check again.
$value = $p;
$count++;
}
Return the results.
[$count, $value];
}
Task 2 is a duplicate of Challenge 340 task 1, and I haven't added any
new languages since then.
Full code on
github.