Perl Weekly Challenge 65: Digit Sum

These are some answers to the Week 65 of the Perl Weekly Challenge organized by Mohammad S. Anwar.

You are given two positive numbers $N and $S.

Write a script to list all positive numbers having exactly $N digits where sum of all digits equals to $S.

Example:

Input:
    $N = 2
    $S = 4

Output:
    13, 22, 31, 40

Digit Sum in Raku

My first attempt to solve the problem would be a pure brute force approach as follows:

use v6;
sub MAIN (Int $nb_digits, Int $sum) {
    for 10 ** ($nb_digits - 1) .. 10 ** $nb_digits - 1 -> $num {
        say $num if $num.comb.sum == $sum;
    }
}

We’re just checking every number in the range.

A slight performance improvement is possible:

use v6;

sub MAIN (Int $nb_digits, Int $sum) {
    my $max = -1 + $sum <= 9 
        ?? $sum * 10 ** ($nb_digits -1) 
        !! 10 ** $nb_digits;
    for 10 ** ($nb_digits - 1) .. $max -> $num {
        say $num if $num.comb.sum == $sum;
    }
}

This is an example output:

$ ./perl6 digit-sum.p6 3 6
105
114
123
132
141
150
204
213
222
231
240
303
312
321
330
402
411
420
501
510
600

Digit Sum in Perl

This is a port to Perl of the above Raku program:

use strict;
use warnings;
use feature qw /say/;

sub sum {
    my $sum_digits = 0;
    $sum_digits += $_ for split //, shift;
    return $sum_digits;
}
my ($nb_digits, $sum) = @ARGV;
for my $num (10 ** ($nb_digits - 1) .. 10 ** $nb_digits - 1 ) {
    say $num if $sum == sum $num;
}

Wrapping up

Note: there was another task in this challenge, but I was extremely busy the whole weekend and did not have time to work on it. This is also the reason why I am publishing this blog post so late. However, task 2 seems interesting, I might come back to it this week if I have more time.

The next week Perl Weekly Challenge has already started. If you want to participate in this challenge, please check https://perlweeklychallenge.org/ and make sure you answer the challenge before 23:59 BST (British summer time) on Sunday, June 28, 2020. And, please, also spread the word about the Perl Weekly Challenge if you can.

Leave a comment

About laurent_r

user-pic I am the author of the "Think Perl 6" book (O'Reilly, 2017) and I blog about the Perl 5 and Raku programming languages.