# Raku: 解 Perl Weekly Challenge 082

### TASK #1 › Common Factors

You are given 2 positive numbers \$M and \$N. Write a script to list all common factors of the given numbers.

``````sub common-factors (Int \$M, Int \$N) {
factors(\$N) ∩ factors(\$M)
}
``````

``````sub factors (Int \$n) {
(1..\$n).grep(-> \$it { \$n %% \$it });
}
``````

`%%` 是「整除於運算子」。`\$a %% \$b``\$a % \$b == 0` 兩者同義。

``````sub common-factors (Int \$a, Int \$b) {
my \$x = min(\$a, \$b);
my @x = (1, 2..\$x/2, \$x).flat;
return @x.grep(-> \$it { \$a %% \$it && \$b %% \$it });
}
``````

(10/14 更新) 經過推友 zard1989 提示，先確認了「兩數之公因數全部都是最大公因數之因數」這件事。於是再改版如下：

``````sub common-factors (Int \$a, Int \$b) {
my \$x = \$a gcd \$b;
return (1..\$x).grep(-> \$n { \$x %% \$n });
}
``````

### TASK #2 › Interleave String

You are given 3 strings; \$A, \$B and \$C. Write a script to check if \$C is created by interleave \$A and \$B. Print 1 if check is success otherwise 0.

``````sub interleaves (Str \$A, Str \$B, Str \$C) {
my @stash;
@stash.push([-1, -1]);

my \$i = 0;
while \$i < \$C.chars && @stash.elems > 0 {
my \$c = \$C.substr(\$i++, 1);
my @stash2 = gather {
while @stash.elems > 0 {
my \$it = @stash.pop();
my \$a = \$A.substr(\$it[0]+1, 1);
my \$b = \$B.substr(\$it[1]+1, 1);
if \$c eq \$a {
take [\$it[0]+1, \$it[1]];
}
if \$c eq \$b {
take [\$it[0], \$it[1]+1];
}
}
};

@stash = @stash2.unique(:with(&[eqv]));
}

return \$i == \$C.chars && @stash.elems > 0 && @stash[0][0].succ == \$A.chars && @stash[0][1].succ == \$B.chars;
}
``````