aboutsummaryrefslogtreecommitdiff
path: root/challenge-150/dave-jacoby/perl/ch-2.pl
blob: 3a48412911f5b2c1463ce3b82da0cd2349feb982 (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
51
52
53
54
55
56
#!/usr/bin/env perl

use strict;
use warnings;
use feature qw{ say postderef signatures state };
no warnings qw{ experimental };

use Term::ReadKey;

display_pretty( square_free_integers() );

sub square_free_integers () {
    my @sfi;
    my $max = 500;

OUTER: for my $i ( 1 .. $max ) {
        my @factors = factors($i);
        for my $f (@factors) {
            my $g = () = grep { /$f/ } @factors;
            next OUTER if $g > 1;
        }
        push @sfi, $i;
    }

    return @sfi;
}

sub factors ( $n ) {
    my @factors;
    my $i = 2;
    while ( $i < $n ) {
        while ( $n % $i == 0 ) {
            $n /= $i;
            push @factors, $i;
        }
        $i++;
    }
    return @factors;
}

sub display_pretty( @arr ) {
    my ( $wchar, undef ) = GetTerminalSize();
    $wchar //= 80;
    my $line;

    while ( scalar @arr > 1 ) {
        my $n = shift @arr;
        $line .= qq{$n, };
        if ( (length $line )+ 5 > $wchar ) {
            say $line;
            $line = '';
        }
    }
    $line .= shift @arr;
    say $line;
}