📘 Computing the sum of digits using Perl 6

📘 Computing the sum of digits using Raku

N. B. Perl 6 has been renamed to Raku. Click to read more.


Calculate the sum of digits of a given number.

The solution of this task is based on the splitmethod that you can call on any object that is convertible to strings.

The following code takes an integer number and splits it into separate characters, one per digit. Then the reduction operator adds up all the digits, and the result is printed.

my $number = 139487854;
say [+] $number.split('');

The conversion of an integer to a string happens at the moment the splitmethod is called. The resulting array contains a number of one-character elements. When they are passed to the [+] operator, which expects numeric data, characters are converted back to numbers so that they can be added up as numbers, not strings.

Compare the presented solution with a straightforward approach, where the given number is treated as a number, and a series of divisions has to be performed to get separate digits:

my $number = 139487854;
my $sum = 0;

while ($number) {
    $sum += $number % 10;
    $number = Int($number / 10);
}
say $sum; # Still prints 49

One thought on “📘 Computing the sum of digits using Perl 6”

Leave a Reply

Your email address will not be published. Required fields are marked *

Retype the CAPTCHA code from the image
Change the CAPTCHA codeSpeak the CAPTCHA code