DEV Community

Kang-min Liu
Kang-min Liu

Posted on

Solving Perl Weekly Challenge 089 -- GCD Sum and the magic square.

We have 2 math puzzles from Perl Weekly Challenge 089 this time around. Their solution look rather naive.

TASK #1 › GCD Sum

Submitted by: Mohammad S Anwar

You are given a positive integer $N.

Write a script to sum GCD of all possible unique pairs between 1 and $N.

Example 1:

Input: 3
Output: 3

gcd(1,2) + gcd(1,3) + gcd(2,3)

Example 2:

Input: 4
Output: 7

gcd(1,2) + gcd(1,3) + gcd(1,4) + gcd(2,3) + gcd(2,4) + gcd(3,4)


Quite literally, we could translate the question to Raku code and get a naive solution:

(1..$N).combinations(2).map(-> ($a, $b) { $a gcd $b }).sum() 
Enter fullscreen mode Exit fullscreen mode

TASK #2 › Magical Matrix

Submitted by: Mohammad S Anwar

Write a script to display matrix as below with numbers 1 - 9. Please make sure numbers
are used once.

[ a b c ] [ d e f ] [ g h i ] 
Enter fullscreen mode Exit fullscreen mode

So that it satisfies the following:

a + b + c = 15 d + e + f = 15 g + h + i = 15 a + d + g = 15 b + e + h = 15 c + f + i = 15 a + e + i = 15 c + e + g = 15 
Enter fullscreen mode Exit fullscreen mode

Without doing any prior analysis of 3x3 magic square, a brute-force searching apporach would db to generate all permutations of the list of 1..9, then remove those that violates the 8 conditions above:

(1..9).permutations.grep( -> ($a, $b, $c, $d, $e, $f, $g, $h, $i) { all( $a + $b + $c == 15, $d + $e + $f == 15, $g + $h + $i == 15, $a + $d + $g == 15, $b + $e + $h == 15, $c + $f + $i == 15, $a + $e + $i == 15, $c + $e + $g == 15, ) } ) 
Enter fullscreen mode Exit fullscreen mode

The .permutations subroutine produce an iterator that give us all possible permutations, and since we are permutating 9 numbers, we let the grep afterward takes 9 separate parameters, which then makes it easier to just copy those conditions from the body of the question.


本文為 解 Perl Weekly Challenge 089 -- 公因數之和與魔方 英文版

Top comments (0)