Course of Raku / Addendum 🆕 / Flow and functions / Subroutines and functional style / Exercises / Digit sum by recursion
Solution: Digit sum by recursion
Here is a possible solution to the task.
Code
sub digit-sum($n) {
return $n if $n < 10;
return $n % 10 + digit-sum($n div 10);
}
say digit-sum(12345);🦋 You can find the source code in the file recursive-digit-sum.raku.
Output
15Comments
- The base case is a single-digit number, which is its own digit sum.
Otherwise the routine peels off the last digit with
$n % 10and recurses on the rest,$n div 10.