# 解 Perl Weekly Challenge 089 -- 公因數之和與魔方

Perl Weekly Challenge 089 兩題都是數學謎題呢。姑且就先用暴力法來解吧。

## TASK #1 › GCD Sum

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)

``(1..\$N).combinations(2).map(-> (\$a, \$b) { \$a gcd \$b }).sum()``

# TASK #2 › Magical Matrix

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 ]
``````

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
``````

``````(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,
)
}
)``````

`.permutations` 函式能逐一產生出所有排列。因為這裡是讓他產生九個數字的排列， 所以後方接的 `grep` 就有九個參數，這麼一來裡面的判斷條件就可以直接從題目本文照抄過來。