Peter’s blog ✴ Week 158 ✴ 28 March 2022

THE WEEKLY CHALLENGE
All about primes

The Perl Camel

Task 2

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.

Perl Weekly’s review

from PW issue 558

Multiple versions of the task are provided! Thank you for sharing your knowledge with us!

This review may cover either or both challenges for this week.

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) . '.';   

13 lines of code

Output from script


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

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain