Peter
Peter Campbell Smith

All about primes

Weekly challenge 158 — 28 March 2022

Week 158 - 28 Mar 2022

Task 2

Task — First series Cuban primes

Write a script to compute first series Cuban primes <= 1000. The first series of Cuban primes are the prime values of 3y^2 + 3y + 1 for y = 1, 2, ....

Please refer to the Wikipedia page for more information.

Examples


Example 1:
7 is a member of the series as
3 * 7^2 + 3 * 7 + 1 =
147 + 21 + 1 =
169, which is prime

Analysis

There seems little benefit in optimising the calculation, but given that we have to test for all values of y, it's worth noting that:

candidate[y]     = 3y^2       + 3y       + 1

candidate[y + 1] = 3(y + 1)^2 + 3(y + 1) + 1
                 = 3y^2 + 9y + 7
                 = candidate[y] + 6(y + 1)

So we can zip through the candidate values by simply adding 6(y + 1) to the previous one, and then is_prime is your friend.

Script


#!/usr/bin/perl

# Peter Campbell Smith - 2022-03-30
# PWC 158 task 2

use v5.28;
use strict;
use warnings;
use utf8;
use Math::Prime::Util 'is_prime';

my ($y, $test, $result);

$test = 7;   # 3 * $y**2 + 3 * $y + 1 for y == 1
for $y (1 .. 1000) {
    last if $test > 1000;
    $result .= qq[$test, ] if is_prime($test);
    $test += 6 * ($y + 1);
}

say qq[The terms of the first Cuban series <= 1000 are:];
say substr($result, 0, -2) . '.';   

Output


The terms of the first series Cuban primes  <= 1000 are:
7, 19, 37, 61, 127, 271, 331, 397, 547, 631, 919.