Generating sexy prime pairs in Raku

This is article about programming. This solves Task 1 of the Perl Weekly Challenge 027. The so-called sexy prime pairs are pairs of prime numbers that differ by 6.

This is article about programming. This solves Task 1 of the Perl Weekly Challenge 022.

The so-called sexy prime pairs are pairs of prime numbers that differ by 6.

Generating prime numbers in Raku is an extremely simple task due to the built-in is-prime method.

Let me demonstrate my straightforward solution, which can be reduced to a one-line probably. I applied a simple optimisation and excluded even numbers from consideration (knowing that 2 does not an cannot have a pair).

my $count = 0;
for 1, 3 ... * -> $a {
    next unless $a.is-prime;

    my $b = $a + 6;
    next unless $b.is-prime;

    say "$a, $b";
    last if ++$count == 10;
}

The program checks if the current number $a is prime, and if so, tests $a + 6 to be also a prime. If so, it prints them both, giving the following output:

5, 11
7, 13
11, 17
13, 19
17, 23
23, 29
31, 37
37, 43
41, 47
47, 53

GitHub repository
Navigation to the Raku challenges post series

Leave a Reply

Your email address will not be published. Required fields are marked *

Retype the CAPTCHA code from the image
Change the CAPTCHA codeSpeak the CAPTCHA code