Created
June 16, 2019 04:51
-
-
Save adamcrussell/4a44db398e8cf0668621524f7aa57fc2 to your computer and use it in GitHub Desktop.
Perl Weekly Challenge 012
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 strict; | |
use warnings; | |
## | |
# The numbers formed by adding one to the products of the smallest primes | |
# are called the Euclid Numbers. Write a script that finds the smallest | |
# Euclid Number that is not prime | |
## | |
use boolean; | |
use LWP::UserAgent; | |
use constant PRIME_URL => "http://primes.utm.edu/lists/small/10000.txt"; | |
sub get_primes{ | |
my @primes; | |
my $ua = new LWP::UserAgent( | |
ssl_opts => {verify_hostname => 0} | |
); | |
my $response = $ua->get(PRIME_URL); | |
my @lines = split(/\n/,$response->decoded_content); | |
foreach my $line (@lines){ | |
my @p = split(/\s+/, $line); | |
unless(@p < 10){ | |
push @primes, @p[1..(@p - 1)]; | |
} | |
} | |
return @primes; | |
} | |
sub find_nth_euclid{ | |
return eval(join("*", @_)) + 1; | |
} | |
sub is_prime{ | |
my($n) = @_; | |
for my $i (2 .. int(sqrt($n))){ | |
return false if(($n % $i) == 0); | |
} | |
return true; | |
} | |
## | |
# Main | |
## | |
my @primes = get_primes(); | |
foreach my $i (0..(@primes - 1)){ | |
my $euclid = find_nth_euclid(@primes[0 .. $i]); | |
if(!is_prime($euclid)){ | |
print "E_" . ($i + 1) . " = $euclid is composite.\n"; | |
exit; | |
} | |
} | |
print "No composite Euclid Number found in the first " . @primes . " primes.\n"; |
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 strict; | |
use warnings; | |
## | |
# Write a script that finds the common directory path, | |
# given a collection of paths and directory separator. | |
## | |
use boolean; | |
## | |
# Main | |
## | |
my @paths; | |
my $common_path; | |
my $seperator = <DATA>; | |
chomp($seperator); | |
while(<DATA>){ | |
push @paths, [split(/\Q$seperator\E/, $_)]; | |
} | |
for(my $i=0; $i < @paths; $i++){ | |
my $in_common = true; | |
my $directory = shift @{$paths[$i]}; | |
for(my $j=0; $j < @paths; $j++){ | |
if($j != $i){ | |
my $d = shift @{$paths[$j]}; | |
if($directory && ($d ne $directory)){ | |
$in_common = false; | |
last; | |
} | |
} | |
} | |
if($in_common){ | |
$common_path .= $directory . $seperator; | |
} | |
else{ | |
last; | |
} | |
} | |
chop($common_path); | |
print "Path in common is $common_path.\n"; | |
__DATA__ | |
/ | |
/a/b/c/d | |
/a/b/cd | |
/a/b/cc | |
/a/b/c/d/e |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment