aboutsummaryrefslogtreecommitdiff
path: root/challenge-133/e-choroba/perl/ch-2.pl
blob: 5744ce336bd6f1645e0b781a7a569f5c314586c3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

use List::Util qw{ sum };

my @primes = (2, 3, 5);

sub prime_factors {
    my ($n) = @_;

    my $p = $primes[-1] + 2;
    while ($p < 1 + $n / 2) {
        push @primes, $p unless grep 0 == $p % $_, @primes;
        $p += 2;
    }

    my $m = $n;
    my @factors;
    for my $p (@primes) {
        if (0 == $m % $p) {
            $m /= $p;
            push @factors, $p;
            redo
        }
    }
    return @factors
}

sub smith_numbers {
    my ($count) = @_;
    my @smith;
    my $n = 4;
    while (@smith < $count) {
        my @factors = prime_factors($n);
        next unless @factors > 1;

        push @smith, $n
            if sum(split //, join "", @factors) == sum(split //, $n);
    } continue {
        ++$n;
    }
    return @smith
}

use Test2::V0;
plan 1;

is [smith_numbers(10)], [4, 22, 27, 58, 85, 94, 121, 166, 202, 265];