P34 - 计算欧拉函数 phi(m)。

作者:Philip Potter

如果 m 是素数,求 phi(m) 的值。欧拉函数在最广泛使用的公钥加密方法之一 (RSA) 中起着重要作用。在本练习中,您应该使用最原始的方法来计算此函数(我们稍后将讨论更智能的方法)。

规范

P34 (**) Calculate Euler's totient function phi(m).
      Euler's so-called totient function phi(m) is defined as the number of
      positive integers r (1 <= r < m) that are coprime to m.

示例

# m = 10: r = 1,3,7,9; thus phi(m) = 4. Note the special case: phi(1) = 1.
> say totient_phi 10
4

源代码: P34-rhebus.pl

use v6;

# from P32-rhebus.pl
sub gcds (Int $a, Int $b) {
    return ($a, $b, *%* ... 0)[*-2];
}

# from P33-rhebus.pl
our sub infix:<coprime> (Int $a, Int $b) { (gcds($a,$b) == 1).Numeric }


# Example 1: iteration
multi totient_phi_i (1      --> Int) { 1 }
multi totient_phi_i (Int $n --> Int) {
    my $total = 0;
    for 1..^$n -> $k { $total++ if $n coprime $k }
    return $total;
}

say "phi($_): ", totient_phi_i $_ for (1..20);

# Example 2: «coprime« hyper operator
multi totient_phi (1      --> Int) { 1 }
multi totient_phi (Int $n --> Int) {
    return 1 if $n ~~ 1;
    return [+] ($n «coprime« list(1..^$n));
}

say "phi($_): ",totient_phi $_ for (1..20);