Peter’s solutions: week 102 — 1 March 2021

THE WEEKLY CHALLENGE
Rare hashes

The Perl Camel

Task 1

Rare numbers

You are given a positive integer $N. Write a script to generate all Rare numbers of size $N.

Please see this page for more information.

Examples


Example 1
Input: $N = 1_000_000
Output: 65, 621770

Analysis

Rare Numbers are - unsurprisingly - rare. My solution finds the first 2 in a matter of seconds and demontstrates that these are the only two under a million.

The next one is 281_089_082 and its square will exceed the capacity of a Perl integer (on a 64-bit machine), so my algorithm will fail.

And I reckon Math::BigInt will be too slow for my simple code, so that's as much as I am reasonably able to do.

Try it 

Try running the script with any input:



example: 1234 - (max 1000000)

Script


#!/usr/bin/perl

# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

use v5.26;    # The Weekly Challenge - 2021-03-01
use utf8;     # Week 102 - task 1 - Rare numbers
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';
use Encode;

rare_numbers(1_000_000);

sub rare_numbers {
    
    my ($n, $i, $ir, %square, $size, $result);
    
    # initialise
    $size = $_[0];
    
    for $i (2 .. $size) {
        
        # make list of squares
        $square{$i ** 2} = 1;
        
        # check for rarity
        $ir = reverse($i);
        if ($square{$i - $ir} and $square{$i + $ir}) {
            $result .= qq[$i, ];
        }
    }
    
    # report
    say qq[\nInput:  $size];
    say qq[Output: ] . substr($result, 0, -2);
}


10 lines of code
Completed after the closing date and not submitted to GitHub

Output


Input:  1000000
Output: 65, 621770

 

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