# [Raku] 如何做質因數分解

Raku 語言中直接提供了 `is-prime` 函式給 Int 型別（整數），能去檢查所指定的整數是否為質數。

``````my Int \$n = @*ARGS[0].Int;
``````

``````(2..*).grep(*.is-prime)
``````

1. `n` 不能被 `p` 整除，則忽略 `p`
2. `n` 能被 `p` 整除，則：
3. 找到一最大的整數 `k`，使 `n` 能被 `n**k` 整除
4. `n``n / p**k`

``````my Int \$n = @*ARGS[0].Int;
my Int \$k = 1;
while \$n %% \$p {
\$n = \$n div \$p;
\$k++;
}
\$k -= 1;
``````

`\$n %% \$p` 這部份所用到的 `%%` 算符， 是用來判別「`\$n` 是否為 `\$p` 的整數倍」，也就是「`\$n` 整除於 `\$p`」的判別式。也可寫成 `\$n % \$p == 0`

``````if \$k > 0 {
push @factors, \$p => \$k;
}
``````

``````if \$n == 1 {
last;
}
``````

``````if \$n.is-prime {
push @factors, \$n => 1;
last;
}
``````

``````say @factors.map({ .key ~ "**" ~ .value  }).join(" * ");
``````

``````#!/usr/bin/env raku

sub prime-factorizatiion(Int \$n is copy) {
my @factors;

for (2..*).grep(*.is-prime) -> \$p {
my \$k = 1;
while \$n %% \$p {
\$n = \$n div \$p;
\$k++;
}
\$k -= 1;

if \$k > 0 {
push @factors, \$p => \$k;
}

if (\$n.is-prime) {
push @factors, \$n => 1;
last;
}
}

return @factors;
}

my \$n = @*ARGS[0].Int;
my @factors = prime-factorizatiion(\$n);

say @factors.map({ .key ~ "**" ~ .value  }).join(" * ");
``````

``````sub prime-factorizatiion(Int \$n is copy) {
...
}
``````

``````# prime-factors 3884831087831
59**1 * 65844594709**1
``````

``````# echo \$((\$( prime-factors 3884831087831 )))
3884831087831
``````