πŸ“˜ Computing the sum of digits using Perl 6

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s