The weekly challenge 252 - Task 1: Special Numbers
1 #!/usr/bin/perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-252/#TASK1 3 # 4 # Task 1: Special Numbers 5 # ======================= 6 # 7 # You are given an array of integers, @ints. 8 # 9 # Write a script to find the sum of the squares of all special elements of the 10 # given array. 11 # 12 ## An element $int[i] of @ints is called special if i divides n, i.e. n % i == 0. 13 ## Where n is the length of the given array. Also the array is 1-indexed for the task. 14 # 15 ## Example 1 16 ## 17 ## Input: @ints = (1, 2, 3, 4) 18 ## Output: 21 19 ## 20 ## There are exactly 3 special elements in the given array: 21 ## $ints[1] since 1 divides 4, 22 ## $ints[2] since 2 divides 4, and 23 ## $ints[4] since 4 divides 4. 24 ## 25 ## Hence, the sum of the squares of all special elements of given array: 26 ## 1 * 1 + 2 * 2 + 4 * 4 = 21. 27 # 28 ## Example 2 29 ## 30 ## Input: @ints = (2, 7, 1, 19, 18, 3) 31 ## Output: 63 32 ## 33 ## There are exactly 4 special elements in the given array: 34 ## $ints[1] since 1 divides 6, 35 ## $ints[2] since 2 divides 6, 36 ## $ints[3] since 3 divides 6, and 37 ## $ints[6] since 6 divides 6. 38 ## 39 ## Hence, the sum of the squares of all special elements of given array: 40 ## 2 * 2 + 7 * 7 + 1 * 1 + 3 * 3 = 63 41 # 42 ############################################################ 43 ## 44 ## discussion 45 ## 46 ############################################################ 47 # 48 # We initialize a variable $result = 0, then we look at each 49 # element in the list and add its square to $result if $i divides n. 50 51 use strict; 52 use warnings; 53 54 special_numbers(1, 2, 3, 4); 55 special_numbers(2, 7, 1, 19, 18, 3); 56 57 sub special_numbers { 58 my @ints = @_; 59 print "Input: (", join(", ", @ints), ")\n"; 60 my $n = @ints; 61 my $result = 0; 62 foreach my $i (1..$n) { 63 my $elem = $ints[$i-1]; 64 if($n % $i == 0) { 65 $result += $elem*$elem; 66 } 67 } 68 print "Output: $result\n"; 69 }