Created
May 27, 2015 20:41
-
-
Save StefanKarpinski/f11505c3153fc2964659 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use Time::HiRes qw(time); | |
sub perl1 { | |
my $k = $_[0]; | |
foreach my $n (10**($k-1) .. 10**($k)-1) { | |
my $front = $n * (10**$k + $n); | |
my $root = int(sqrt($front)); | |
foreach my $t ($root-2 .. $root+2) { | |
my $back = $t * ($t - 1); | |
last if length($t) > $k; | |
last if $back > $front; | |
if ($back == $front) { | |
print STDERR "$n$t\n"; | |
last; | |
} | |
} | |
} | |
} | |
sub perl2 { | |
my $k = $_[0]; | |
foreach my $a (10**($k-1) .. 10**($k)-1) { | |
my $front = $a * (10**$k + $a); | |
my $root = int($front**0.5); | |
foreach my $b ($root-1 .. $root+1) { | |
my $back = $b * ($b - 1); | |
last if $back > $front; | |
next if log($b)/log(10) > $k; | |
if ($front == $back) { | |
print STDERR "$a$b\n" | |
} | |
} | |
} | |
} | |
my $digits = $ARGV[0] // 2; | |
die "Number of digits must be even and non-zero! You said [$digits]\n" | |
unless $digits > 0 and $digits % 2 == 0 and int($digits) eq $digits; | |
my $k = $digits/2; | |
for (1 .. 10) { | |
my $start = time(); | |
perl1($k); | |
my $end = time(); | |
print "perl1,$digits,", $end-$start, "\n"; | |
my $start = time(); | |
perl2($k); | |
my $end = time(); | |
print "perl2,$digits,", $end-$start, "\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment