RogerBW's Blog

The Weekly Challenge 170: Kronecker's Primorial 23 June 2022

I’ve been doing the Weekly Challenges. The latest involved primes and an unusual form of matrix multiplication. (Note that this is open until 26 June 2022.)

Task 1: Primorial Numbers

Write a script to generate the first 10 Primorial Numbers.

In other words a sort of "prime factorial": 2, 2×3, 2×3×5, etc. (though by convention the list starts at 1). This was touched on in #155.1, though then I at least didn't split out their generation into a separate function.

I reuse my existing code to generate a list of primes. To keep the list to a manageable size, I also bring back nthprimelimit that I originally wrote for #146.1, i.e. a function that reasonably cheaply returns an upper bound for the nth prime number. (So if I'm looking at the first ten primorial numbers, I need the first nine primes; the function gives me a limit of 27, so I generate only the primes up to that.)

Raku:

sub nthprimelimit($n) {
    my $m=15;
    if ($n >= 6) {
        $m=floor(1+$n*log($n*log($n)));
    }
    return $m;
}

Then the main body of the work becomes relatively simple.

sub primorial($ct) {

Initialise the output list. (1 not being prime or the product of primes.)

    my @o=(1);

For each of the primes…

    for genprimes(nthprimelimit($ct)) -> $p {

Multiply the last value in the list by the new prime, and push it on.

        push @o,@o[*-1] * $p;

The nth prime limit function isn't exact, so it's possible that I'll get more primes than I actually need. So bail out if I've got enough.

        if (@o.elems >= $ct) {
            last;
        }
    }
    return @o;
}

This looks pretty much the same in all the other languages, except Ruby – for I already have the prime library which gives me an infinite sequence of primes reasonably cheaply. And in Perl, I'm finally giving up on my home-grown primality code and moving over to Math::Prime::Util with its next_prime function:

sub primorial($ct) {
  my @o = (1);
  my $lp = 1;
  while (scalar @o < $ct) {
    $lp = next_prime($lp);
    push @o,$o[-1] * $lp;
  }
  return \@o;
}

Task 2: Kronecker Product

You are given 2 matrices.

Write a script to implement Kronecker Product on the given 2 matrices.

This turns out to be a sort of combinatorial multiplication: the second matrix is multiplied linearly by each element in the first, and the results arranged matching those elements. Which gives a way of working out how to do it: if the two input matrices have size (ax, ay) and (bx, by), then for each set of output coordinates (x, y), the result will be the product of the element of a at (x / bx, y / by) and the element of b at (x % bx, y % by). (Assume integer division of course. And this is one of the few cases where Lua's 1-based indices make a difference; they aren't as annoying in general as I thought they'd be, but they certainly are here.)

I use actual variables for ax etc. for clarity, and assume that all rows are of equal length in the input. Rust is one of the majority of languages I'm using here that lets me say "this variable is an integer, dammit, and everything involving it will also be an integer unless I tell you otherwise", so has no need for a special integer-division operator.

fn kronecker(a: Vec<Vec<usize>>, b: Vec<Vec<usize>>) -> Vec<Vec<usize>> {
    let mut o = Vec::new();
    let ax = a[0].len();
    let ay = a.len();
    let bx = b[0].len();
    let by = b.len();
    for y in 0..ay * by {
        let byi = y % by;
        let ayi = y / by;
        let mut row = Vec::new();
        for x in 0..ax * bx {
            let bxi = x % bx;
            let axi = x / bx;
            row.push(a[ayi][axi] * b[byi][bxi]);
        }
        o.push(row);
    }
    o
}

Full code on github.

See also:
The Weekly Challenge 146: Curious Prime
The Weekly Challenge 155: Pisano's Fortune

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.

Search
Archive
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 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 crystal 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 2021 hugo 2022 hugo 2023 hugo 2024 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