解 Perl Weekly Challenge 089 -- 公因數之和與魔方
作者:gugod 發佈於: #rakuPerl Weekly Challenge 089 兩題都是數學謎題呢。姑且就先用暴力法來解吧。
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)
如果直接將題意「翻譯」成 Raku 程式碼的話,就會得到直觀暴力解:
(1..$N).combinations(2).map(-> ($a, $b) { $a gcd $b }).sum()
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 ]
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
這題就是用程式解 3×3 魔方啦。如果完全不事先分析魔方特性,只靠暴力法搜尋來解的話,就等同於先產生出 1..9 的排列,再過濾掉任何不符前述八條算式者。
(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
就有九個參數,這麼一來裡面的判斷條件就可以直接從題目本文照抄過來。