Peter’s blog ✴ Week 375 ✴ 25 May 2026
THE WEEKLY CHALLENGE
Single and beautiful
You are given a number $num and a digit $k.
Write a script to find the K-Beauty of $num. The K-Beauty of an integer number is defined as the number of substrings of $num when it is read as a string which have a length of $k
and are integer divisors of $num.
Example 1 Input: $num = 240, $k = 2 Output: 2 Substring with length 2: 24: 240 is divisible by 24 40: 240 is divisible by 40 Example 2 Input: $num = 1020, $k = 2 Output: 3 Substring with length 2: 10: 240 is divisible by 10 02: 240 is divisible by 2 20: 240 is divisible by 20 Example 3 Input: $num = 444, $k = 2 Output: 0 Substring with length 2: First '44': 444 is not divisible by 44 Second '44': 444 is not divisible by 44 Example 4 Input: $num = 17, $k = 2 Output: 1 Substring with length 2: 17: 17 is divisible by 17 Example 5 Input: $num = 123, $k = 1 Output: 2 Substring with length 1: 1: 123 is divisible by 1 2: 123 is not divisible by 2 3: 123 is divisible by 3
This is not hard to do with a simple search over all possible substrings of the stated length, which completes in negligible time for any reasonable length number. The only slight wrinkle is that substrings which are all zeroes - eg 000 - must be skipped.
Most K-beautiful numbers contain zeroes, and that tendency increases
as $k increases and as the K-beauty, ie the number of divisors, increases.
#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2026-05-25 use utf8; # Week 375 - task 2 - Find K-Beauty use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; use Encode; find_KBeauty(240, 2); find_KBeauty(1001, 2); find_KBeauty(100100, 4); find_KBeauty(2001600, 5); find_KBeauty(10250, 2); find_KBeauty(160320, 2); find_KBeauty(1015050, 3); sub find_KBeauty { my ($number, $k, $l, $sub, @subs, $s); # initialise ($number, $k) = @_; $l = length($number); # loop over substrings and test for beauty for $s (0 .. $l - $k) { $sub = substr($number, $s, $k); next unless $sub > 0; push @subs, $sub if $number / $sub == int($number / $sub); } # report say qq[\nInput: \$number = $number, \$k = $k]; say qq[Output: ] . scalar @subs . (scalar @subs ? q[ - ] . join(q[, ], @subs) : ''); }
11 lines of code
Input: $number = 240, $k = 2 Output: 2 - 24, 40 Input: $number = 1001, $k = 2 Output: 1 - 01 Input: $number = 100100, $k = 4 Output: 3 - 1001, 0010, 0100 Input: $number = 2001600, $k = 5 Output: 3 - 20016, 00160, 01600 Input: $number = 10250, $k = 2 Output: 4 - 10, 02, 25, 50 Input: $number = 160320, $k = 2 Output: 5 - 16, 60, 03, 32, 20 Input: $number = 1015050, $k = 3 Output: 5 - 101, 015, 150, 505, 050
Any content of this website which has been created by Peter Campbell Smith is in the public domain