Peter
Peter Campbell Smith

Pernicious and weird

Weekly challenge 156 — 14 March 2022

Week 156: 14 Mar 2022

Task 1

Task — Pernicious numbers

Write a script to calculate the first 10 Pernicious Numbers. A pernicious number is a positive integer which has prime number of ones in its binary representation.

Examples


Example 1:
The first pernicious number is 3 since the binary 
representation of 3 = (11) and 1 + 1 = 2, which is a 
prime.

Analysis

Pernicious numbers can presumably have any number of zeroes as wellas the 1s.

Perl conveniently has the $binary = sprintf('%b', $n) construct which quickly gives us the binary representation of $n, and we can then count the 1s like this:

@ones = $binary =~ m|1|g;

This rather counterintuitive statement works because the m|| returns a list of matches which can then be assigned to an array, and the number of elements in the array thus gives the number of matches, or in our case, the number of 1s.

And as we've dealt with the generation of primes often in the last few weeks I took the lazy way out and used Math::Prime::Util 'is_prime' to determine whether the count is prime.

Script


#!/usr/bin/perl

# Peter Campbell Smith - 2022-03-17
# PWC 156 task 1

use v5.28;
use strict;
use warnings;
use utf8;
use Math::Prime::Util 'is_prime';

my ($found, $j, $binary, @ones, $count);

# loop over numbers 1 to big
$found = 0;
for $j (1 .. 100) {
    
    say qq[Pernicious numbers:];
    
    # convert to binary
    $binary = sprintf('%b', $j);
    
    # get a list of the '1' matches and assign it to an array
    @ones = $binary =~ m|1|g;
    
    # count the number of elements in the array
    $count = scalar @ones;
    
    # and we have an answer if the count is prime
    next unless is_prime($count);
    say $j; 
    last if $found ++ == 9;
}

Output


Pernicious numbers:
3
5
6
7
9
10
11
12
13
14

 

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