The weekly challenge 243 - Task 2: Floor Sum

 1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-243/#TASK2
 3 #
 4 # Task 2: Floor Sum
 5 # =================
 6 #
 7 # You are given an array of positive integers (>=1).
 8 #
 9 # Write a script to return the sum of floor(nums[i] / nums[j]) where
10 # 0 <= i,j < nums.length. The floor() function returns the integer part
11 # of the division.
12 #
13 ## Example 1
14 ##
15 ## Input: @nums = (2, 5, 9)
16 ## Output: 10
17 ##
18 ## floor(2 / 5) = 0
19 ## floor(2 / 9) = 0
20 ## floor(5 / 9) = 0
21 ## floor(2 / 2) = 1
22 ## floor(5 / 5) = 1
23 ## floor(9 / 9) = 1
24 ## floor(5 / 2) = 2
25 ## floor(9 / 2) = 4
26 ## floor(9 / 5) = 1
27 #
28 ## Example 2
29 ##
30 ## Input: @nums = (7, 7, 7, 7, 7, 7, 7)
31 ## Output: 49
32 #
33 ############################################################
34 ##
35 ## discussion
36 ##
37 ############################################################
38 #
39 # Sum up the calculated floor(nums[i]/nums[$j]) for all combinations.
40 
41 use strict;
42 use warnings;
43 
44 floor_sum(2, 5, 9);
45 floor_sum(7, 7, 7, 7, 7, 7, 7);
46 
47 sub floor_sum {
48    my @nums = @_;
49    my $result = 0;
50    print "Input: (" . join(", ", @nums) . ")\n";
51    foreach my $i (0..$#nums) {
52       foreach my $j (0..$#nums) {
53          $result += int($nums[$i] / $nums[$j]);
54       }
55    }
56    print "Output: $result\n";
57 }