RogerBW's Blog

The Weekly Challenge 241: Prime Triplets 05 November 2023

I’ve been doing the Weekly Challenges. The latest involved sequence searching and another nested sort. (Note that this ends today.)

Task 1: Arithmetic Triplets

You are given an array (3 or more members) of integers in increasing order and a positive integer.

Write a script to find out the number of unique Arithmetic Triplets satisfying the following rules:

a) i < j < k b) nums[j] - nums[i] == diff c) nums[k] - nums[j] == diff

My approach is a straightforward one: turn the input numbers into a set, then for each number n search the set for (n + diff) and (n + diff × 2). (This may break in interesting ways if numbers are duplicated, but the problem statement leaves this undefined.)

Challenge 239 task 2 has a similar "filter a list and return the count of results" approach.


sub arithmetictriplets($a, $diff) {
  my %vs = map {$_ => 1} @{$a};
  return grep {(exists $vs{$_+$diff}) && (exists $vs{$_+$diff*2})} @{$a};

I rather like the PostScript approach too. (All right, it does rely on my library code for filter and toset.)

/arithmetictriplets {
    0 dict begin
    /diff exch def
    /nums exch def
    /ns nums toset def
    nums { diff add dup ns exch known
           exch diff add ns exch known
           and } filter length
} bind def

Task 2: Prime Order

You are given an array of unique positive integers greater than 2.

Write a script to sort them in ascending order of the count of their prime factors, tie-breaking by ascending value.

It's been a while since I got out the prime factoring code—Challenge 169 task 2 in fact. The multi-key sort is as seen in Challenge 238 task 2. Given those existing top and bottom layers, the new code is relatively straightforward. (I won't include the primality code here, though I converted it afresh for Scala.)


function primefactorcount(n) {
    return Array.of(...primefactor(n).values()).reduce((x, y) => x + y, 0);

function primeorder(ints) {
    let b = ints;
    let c = new Map;
    for (let n of ints) {
        c.set(n, primefactorcount(n));
    b.sort(function(aa, bb) {
        if (c.get(aa) == c.get(bb)) {
            return aa - bb;
        } else {
            return c.get(aa) - c.get(bb);
    return b;

For some of the languages I added an integer square root function simply to keep floating point out of the execution path. It's not time-critical in these functions, being called just once in genprimes and once in primefactor, but I don't like using floats where I don't have to. It's all fairly straightforard anyway, using a modified chop search, so here's the Rust:

fn isqrt(s: usize) -> usize {
    if s <= 1 {
        return s;
    let mut x0 = s / 2;
    let mut x1 = (x0 + s / x0) / 2;
    while x1 < x0 {
        x0 = x1;
        x1 = (x0 + s / x0) / 2;
    return x0;

Full code on github.

Comments on this post are now closed. If you have particular grounds for adding a late comment, comment on a more recent post quoting the URL of this one.

Tags 1920s 1930s 1940s 1950s 1960s 1970s 1980s 1990s 2000s 2010s 3d printing action advent of code aeronautics aikakirja anecdote animation anime army astronomy audio audio tech aviation base commerce battletech beer boardgaming book of the week bookmonth chain of command children chris chronicle church of no redeeming virtues cold war comedy computing contemporary cornish smuggler cosmic encounter coup covid-19 crime cthulhu eternal cycling dead of winter doctor who documentary drama driving drone ecchi economics en garde espionage essen 2015 essen 2016 essen 2017 essen 2018 essen 2019 essen 2022 essen 2023 existential risk falklands war fandom fanfic fantasy feminism film firefly first world war flash point flight simulation food garmin drive gazebo genesys geocaching geodata gin gkp gurps gurps 101 gus harpoon historical history horror hugo 2014 hugo 2015 hugo 2016 hugo 2017 hugo 2018 hugo 2019 hugo 2020 hugo 2022 hugo-nebula reread in brief avoid instrumented life javascript julian simpson julie enfield kickstarter kotlin learn to play leaving earth linux liquor lovecraftiana lua mecha men with beards mpd museum music mystery naval noir non-fiction one for the brow opera parody paul temple perl perl weekly challenge photography podcast politics postscript powers prediction privacy project woolsack pyracantha python quantum rail raku ranting raspberry pi reading reading boardgames social real life restaurant reviews romance rpg a day rpgs ruby rust scala science fiction scythe second world war security shipwreck simutrans smartphone south atlantic war squaddies stationery steampunk stuarts suburbia superheroes suspense television the resistance the weekly challenge thirsty meeples thriller tin soldier torg toys trailers travel type 26 type 31 type 45 vietnam war war wargaming weather wives and sweethearts writing about writing x-wing young adult
Special All book reviews, All film reviews
Produced by aikakirja v0.1