The weekly challenge 375 - Task 2: Find K-Beauty
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-375/#TASK2 3 # 4 # Task 2: Find K-Beauty 5 # ===================== 6 # 7 # You are given a number and a digit (k). 8 # 9 # Write a script to find the K-Beauty of the given number. The K-Beauty of an 10 # integer number is defined as the number of substrings of given number when it 11 # is read as a string has length of ‘k’ and is a divisor of given number. 12 # 13 ## Example 1 14 ## 15 ## Input: $num = 240, $k = 2 16 ## Output: 2 17 ## 18 ## Substring with length 2: 19 ## 24: 240 is divisible by 24 20 ## 40: 240 is divisible by 40 21 # 22 ## Example 2 23 ## 24 ## Input: $num = 1020, $k = 2 25 ## Output: 3 26 ## 27 ## Substring with length 2: 28 ## 10: 240 is divisible by 10 29 ## 02: 240 is divisible by 2 30 ## 20: 240 is divisible by 20 31 # 32 ## Example 3 33 ## 34 ## Input: $num = 444, $k = 2 35 ## Output: 0 36 ## 37 ## Substring with length 2: 38 ## First "44": 444 is not divisible by 44 39 ## Second "44": 444 is not divisible by 44 40 # 41 ## Example 4 42 ## 43 ## Input: $num = 17, $k = 2 44 ## Output: 1 45 ## 46 ## Substring with length 2: 47 ## 17: 17 is divisible by 17 48 # 49 ## Example 5 50 ## 51 ## Input: $num = 123, $k = 1 52 ## Output: 2 53 ## 54 ## Substring with length 1: 55 ## 1: 123 is divisible by 1 56 ## 2: 123 is not divisible by 2 57 ## 3: 123 is divisible by 3 58 # 59 ############################################################ 60 ## 61 ## discussion 62 ## 63 ############################################################ 64 # 65 # We just create all substrings of length k and count them if $num 66 # is divisible by that number. 67 68 use v5.36; 69 70 find_k_beauty(240, 2); 71 find_k_beauty(1020, 2); 72 find_k_beauty(444, 2); 73 find_k_beauty(17, 2); 74 find_k_beauty(123, 1); 75 76 sub find_k_beauty($num, $k) { 77 say "Input: num = $num, k = $k"; 78 my $n = $num; 79 my $k_beauty = 0; 80 while(length($n) >= $k) { 81 my $s = substr($n, 0, $k); 82 $s =~ s/^0*//; 83 $n = substr($n, 1); 84 $k_beauty++ unless $num % $s; 85 } 86 say "Output: $k_beauty"; 87 }