The weekly challenge 393 - Task 1: Pythagoras Multiplied
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-393/#TASK1 3 # 4 # Task 1: Pythagoras Multiplied 5 # ============================= 6 # 7 # You are given a positive integer n. 8 # 9 # Find the number of all positive integer triplets (a, b, c) so that a^2 + b^2 10 # = c^2 and a, b and c are integers <= n. 11 # 12 ## Example 1 13 ## 14 ## Input: $n = 20 15 ## Output: 12 16 ## 17 ## (3,4,5), (4,3,5), (5,12,13),(6,8,10), 18 ## (8,6,10), (8,15,17), (9,12,15),(12,5,13), 19 ## (12,9,15),(12,16,20),(15,8,17),(16,12,20) 20 # 21 ## Example 2 22 ## 23 ## Input: $n = 7 24 ## Output: 2 25 ## 26 ## (3,4,5),(4,3,5) 27 # 28 ## Example 3 29 ## 30 ## Input: $n = 1 31 ## Output: 0 32 # 33 ## Example 4 34 ## 35 ## Input: $n = 15 36 ## Output: 8 37 # 38 ## Example 5 39 ## 40 ## Input: $n = 30 41 ## Output: 22 42 # 43 ############################################################ 44 ## 45 ## discussion 46 ## 47 ############################################################ 48 # 49 # We simply create all possible combinations for a, b and c and count 50 # the ones where a^2 + b^2 == c^2. 51 52 use v5.36; 53 54 55 pythagorasmultiplied(20); 56 pythagorasmultiplied(7); 57 pythagorasmultiplied(1); 58 pythagorasmultiplied(15); 59 pythagorasmultiplied(30); 60 61 sub pythagorasmultiplied($n) { 62 say "Input: $n"; 63 my $count = 0; 64 foreach my $i (1..$n) { 65 foreach my $j (1..$n) { 66 foreach my $k (1..$n) { 67 if($i*$i + $j*$j == $k*$k) { 68 $count++; 69 } 70 } 71 } 72 } 73 say "Output: $count"; 74 } 75