RogerBW's Blog

The Weekly Challenge 147: Truncating the Pentagon 11 January 2022

I’ve been doing the Weekly Challenges. The latest involved prime searches and pentagonal numbers. (Note that this is open until 16 January 2022.)

Task 1: Truncatable Prime

Write a script to generate first 20 left-truncatable prime numbers in base 10.

A left-truncatable prime is a prime number which, in a given base, contains no 0, and if the leading left digit is successively removed, then all resulting numbers are primes.

The sequence of these primes – which in base 10 is finite – is at the OEIS.

This is clearly a job for a hash. Assume that each of these first 20 numbers is N or below. Then all the truncations of them, which I'll have to test for primality, are also N or below. So I start with Eratosthenes (the same generator I used in last week's challenge 1); and given the constraint, it's probably easier to work with strings than with numbers even in a language that cares about the difference. Here's the Rust:

fn ltruncprimes(count: usize) -> Vec<u32> {
    let mut out: Vec<u32>=Vec::new();
    let mut lt=0;
    let p =
        genprimes(500).iter().map(|i| i.to_string()).collect::<Vec<String>>();
    let pp: HashSet<String>=HashSet::from_iter(p.clone());

At this point p is a list of the primes as strings, and pp lets me look up any string to see whether it's a prime. (The "contains no 0" constraint is handled automatically, because no string representation of a number will have a leading zero, and each relevant substring of the candidate prime will be tested.)

So we build each slice of characters, see if it's in the table of prime strings, and if not bail out of the loop.

    for pc in p {
        let l=pc.len()-1;
        let mut c=true;
        for i in 1..=l {
            if !pp.contains(&pc[i..=l]) {

If all the sub-primes were present, push it (as a number) onto the output list.

        if c {
            lt += 1;
            if lt >= count {

The main difference between languages is whether a string slice takes an end character or a range of indices (Rust, Python, most of the other language), or a length (Perl, PostScript). Every language here has some sort of reasonably clean string slicing approach.

Task 2: Pentagon Numbers

Write a script to find the first pair of Pentagon Numbers whose sum and difference are also a Pentagon Number.

Pentagon numbers can be defined as P(n) = n(3n - 1)/2.

And they can be found in the OEIS of course.

I ended up trading off memory usage for speed, using a cache of pentagonal numbers rather than testing individually for pentagonality (which would involve a square root or similar), and filling it with as-needed calculation.

In Raku, the helper function:

sub pentagon($n) {
    return $n*(3*$n-1)/2;

sub pentpair {

Set up the forward and reverse lookup tables. Forward is index to value, a simple array; reverse is value to index, a hash.

    my @fpent=[0];
    my %rpent;
    my $mx=0;
    my $a=1;
    while (1) {

$a is the index of the larger pentagonal number being considered in each pass. If we don't already have the forward and reverse pentagon tables filled up to $a, do that now.

        while ($mx < $a) {
            push @fpent,pentagon($mx);

Now test each lower index as a $b value.

        for 1..$a-1 -> $b {

Checking the difference is cheaper than checking the sum, so we'll do that first.

            my $d=@fpent[$a]-@fpent[$b];

If this is valid, we'll already have a cache entry for it without having to extend the cache. So only in this case do we carry on testing.

            if (%rpent{$d}:exists) {

Now we look at the sum.

                my $s=@fpent[$a]+@fpent[$b];

If necessary, extend the cache until the highest cached entry is no lower than the sum.

                while ($s > @fpent[$mx]) {
                    push @fpent,pentagon($mx);

Now see if that sum value is in the cache, and if so then print the finding and exit.

                if (%rpent{$s}:exists) {
                    print "P($a) + P($b) = @fpent[$a] + @fpent[$b] = $s = P(%rpent{$s})\n";
                    print "P($a) + P($b) = @fpent[$a] + @fpent[$b] = $d = P(%rpent{$d})\n";
                    exit 0;

I didn't tackle this one in PostScript because of the need for arbitrarily large lookup tables. I did use my Rust code, without the exit at first success, to find:

P(2167) + P(1020) = 7042750 + 1560090 = 8602840 = P(2395)
P(2167) - P(1020) = 7042750 - 1560090 = 5482660 = P(1912)

P(91650) + P(52430) = 12599537925 + 4123331135 = 16722869060 = P(105587)
P(91650) - P(52430) = 12599537925 - 4123331135 = 8476206790 = P(75172)

P(110461) + P(95506) = 18302393551 + 13682046301 = 31984439852 = P(146024)
P(110461) - P(95506) = 18302393551 - 13682046301 = 4620347250 =  P(55500)

P(121168) + P(111972) = 22022465752 + 18806537190 = 40829002942 = P(164983)
P(121168) - P(111972) = 22022465752 - 18806537190 = 3215928562 = P(46303)

P(129198) + P(73745) = 25038120207 + 8157450665 = 33195570872 = P(148763)
P(129198) - P(73745) = 25038120207 - 8157450665 = 16880669542 = P(106084)

P(224159) + P(186517) = 75370773842 + 52182793675 = 127553567517 = P(291609)
P(224159) - P(186517) = 75370773842 - 52182793675 = 23187980167 = P(124333)

Full code on github.

See also:
The Weekly Challenge 146: Curious Prime

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 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