Last active
May 15, 2019 03:29
-
-
Save adamcrussell/df2c8cd5a6f2ca395c642db7852ae67a to your computer and use it in GitHub Desktop.
Perl Weekly Challenge 008
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 computes the first five perfect numbers. | |
# A perfect number is an integer that is the sum of its positive | |
# proper divisors (all divisors except itself). | |
## | |
use constant PERFECT_COUNT => 5; | |
sub factor{ | |
my($n) = @_; | |
my @factors = (1); | |
foreach my $j (2..sqrt($n)){ | |
push @factors, $j if $n % $j == 0; | |
push @factors, ($n / $j) if $n % $j == 0 && $j ** 2 != $n; | |
} | |
return @factors; | |
} | |
my $i = 2; | |
my $count = 0; | |
do{ | |
my @factors = factor($i); | |
my $sum = unpack("%32I*", pack("I*", @factors)); | |
if($sum == $i){ | |
print "$i "; | |
$count++; | |
} | |
$i++; | |
}while($count < PERFECT_COUNT); | |
print "\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 function, "center", whose argument is a list of strings, which | |
# will be lines of text. The function should insert spaces at the beginning | |
# of the lines of text so that if they were printed, the text would be | |
# centered, and return the modified lines. | |
## | |
sub center{ | |
my @words = @_; | |
my @padded_words; | |
my %line_length; | |
my $max_length = -1; | |
my $center; | |
my $i = 0; | |
foreach my $line (@words){ | |
$line_length{$i} = do{ | |
$line =~ tr/ [a-z][A-Z]//; | |
}; | |
$max_length = $line_length{$i} if $line_length{$i} > $max_length; | |
$i++; | |
} | |
$center = int($max_length / 2); | |
for(my $i = 0; $i < @words; $i++){ | |
my $middle = int($line_length{$i} / 2); | |
my $padding = $center - $middle; | |
$padded_words[$i] = " " x $padding . $words[$i]; | |
} | |
return @padded_words; | |
} | |
## | |
# Main | |
## | |
my @words; | |
do{ | |
local $/; | |
@words = split(/\n/, <DATA>); | |
}; | |
my @centered = center(@words); | |
foreach my $w (@centered){ | |
print "$w\n"; | |
} | |
__DATA__ | |
This | |
is | |
a test of the | |
center function |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment