aboutsummaryrefslogtreecommitdiff
path: root/challenge-150/james-smith/perl/ch-2.pl
blob: 95b4f2464cce92b4a1af98d8baf6c06b52644dda (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
57
58
#!/usr/local/bin/perl

use strict;

use warnings;
use feature qw(say);
use Test::More;
use Benchmark qw(cmpthese timethis);
use Data::Dumper qw(Dumper);

cmpthese( 500_000, {
  'grep' => sub { non_square(   100 ) },
  'for'  => sub { non_square_x( 100 ) },
});

cmpthese( 50_000, {
  'grep' => sub { non_square(   1000 ) },
  'for'  => sub { non_square_x( 1000 ) },
});

cmpthese( 5_000, {
  'grep' => sub { non_square(   10_000 ) },
  'for'  => sub { non_square_x( 10_000 ) },
});

cmpthese( 500, {
  'grep' => sub { non_square(   100_000 ) },
  'for'  => sub { non_square_x( 100_000 ) },
});

cmpthese( 100, {
  'grep' => sub { non_square(   1_000_000 ) },
  'for'  => sub { non_square_x( 1_000_000 ) },
});

sub non_square {
  my($N,@p2) = ($_[0],4);
  for(my$c=3;$c*$c<$N;$c+=2){
    ($_>$c)?((push@p2,$c*$c),last):$c*$c%$_||last for@p2;
  }
  return grep{my$t=$_;!grep{!($t%$_)}@p2}1..$N;
}

sub non_square_x {
  my ( $N, @p2, @r ) = ( @ARGV ? $ARGV[0] : 500 , 4 );

  P: for ( my $c = 3; $c*$c <= $N; $c += 2 ) {
    $_ > $c  ? last : $c*$c % $_ || next P for @p2;
    push @p2, $c*$c;
  }

  O: for my $t ( 1 .. $N ) {
    $_ > $t  ? last :    $t % $_ || next O for @p2;
    push @r, $t;
  }

  @r;
}