P41 - 哥德巴赫组合列表。

作者:菲利普·波特

规范

P41 (**) A list of Goldbach compositions.
  Given a range of integers by its lower and upper limit, print a list of
   all even numbers and their Goldbach composition.

示例

> goldbach-list 9,20
10 = 3 + 7
12 = 5 + 7
14 = 3 + 11
16 = 3 + 13
18 = 5 + 13
20 = 3 + 17

在大多数情况下,如果一个偶数可以写成两个素数的和,那么其中一个素数非常小。极少数情况下,这两个素数都大于 50。尝试找出在 2 到 3000 的范围内有多少种这样的情况。

示例(打印限制为 50)

> goldbach-list 1,2000,50
992 = 73 + 919
1382 = 61 + 1321
1856 = 67 + 1789
1928 = 61 + 1867

源代码:P41-rhebus.pl

use v6;

# From P31-rhebus.pl again
sub is_prime (Int $n) {
    for 2..sqrt $n -> $k {
        return Bool::False if $n %% $k;
    }
    return Bool::True;
}

# require even arguments
sub goldbach (Int $n where {$^a > 2 && $^a %% 2}) {
    for 2..$n/2 -> $k {
        if is_prime($k) && is_prime($n-$k) {
            return ($k, $n-$k);
        }
    }
    # actually, it's more likely a logic error than a refutation :)
    die "Goldbach's conjecture is false! $n cannot be separated into two primes!"
}

# Here we demonstrate an optional parameter with a default value
sub goldbach-list (Int $low, Int $high, Int $limit = 1) {
    for $low .. $high -> $n {
        next if $n % 2; # skip invalid goldbach numbers
        next if $n == 2;
        my @pair = goldbach($n);
        say "$n = ", @pair.join(' + ') if @pair[0] > $limit;
    }
}

goldbach-list 9,20;
goldbach-list 2,1000,10;