# RabbitFarm

### 2021-12-05

#### Like, It’s Just the First Ten Numbers Man!

The examples used here are from The Weekly Challenge problem statement and demonstrate the working solution.

## Part 1

Write a script to find lowest 10 positive integers having exactly 8 divisors

### Solution

``````
use strict;
use warnings;
sub factor{
my(\$n) = @_;
my @factors = (1, \$n);
foreach my \$j (2..sqrt(\$n)){
push @factors, \$j if \$n % \$j == 0;
push @factors, (\$n / \$j) if \$n % \$j == 0 && \$j ** 2 != \$n;
}
return @factors;
}

sub first_ten_with_eight{
my \$i = 0;
my @first_ten;
do{
my @factors = factor(\$i);
push @first_ten, \$i if @factors == 8;
\$i++;
}while(@first_ten != 10);
return @first_ten;
}

MAIN:{
print join(", ", first_ten_with_eight()) . "\n";
}
``````

### Sample Run

``````
\$ perl perl/ch-1.pl
24, 30, 40, 42, 54, 56, 66, 70, 78, 88
``````

### Notes

I have re-used that `factor()` function quite a bit for these challenges, especially recently. My blog writing has been fairly terse recently and as much as I'd like to be a bit more verbose I really am not sure if there all that much more to say about this code that hasn't been said before!

## Part 2

You are given positive integers, \$m and \$n. Write a script to find total count of integers created using the digits of \$m which is also divisible by \$n.

### Solution

``````
use strict;
use warnings;
##
# You are given positive integers, \$m and \$n.
# Write a script to find total count of integers
# created using the digits of \$m which is also
# divisible by \$n.
##
use Data::PowerSet q/powerset/;

sub like_numbers{
my(\$m, \$n) = @_;
my @divisible;
for my \$subset (@{powerset(split(//, \$m))}){
my \$i = join("", @\$subset);
push @divisible, \$i if \$i && \$i != \$m && \$i % \$n == 0;
}
return @divisible;
}

MAIN:{
print like_numbers(1234, 2) . "\n";
print like_numbers(768, 4) . "\n";
}
``````

### Sample Run

``````
\$ perl perl/ch-2.pl
9
3
``````

### Notes

I've been making more use of `Data::PowerSet` recently that I would have expected! If anyone is interested in seeing an implementation of the Power Set calculations see my C++ solution links below. While not Perl the code is quite readable and should be adaptable easy to other languages. There is also a Rosetta Code entry for Power Set but, frankly, many of the submissions there, especially the C++ and Perl ones are overly convoluted in my opinion. Or at least much more so than the way I implemented it, which I would think would be the more common method but I guess not!

## References

Challenge 141

Power Set Defined

Data::PowerSet

Rosetta Code Entry: Power Set

C++ Solutions: Part 1

C++ Solutions: Part 2

posted at: 16:47 by: Adam Russell | path: /perl | permanent link to this entry