Skip to content

Instantly share code, notes, and snippets.

@adamcrussell
Last active May 15, 2019 03:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamcrussell/df2c8cd5a6f2ca395c642db7852ae67a to your computer and use it in GitHub Desktop.
Save adamcrussell/df2c8cd5a6f2ca395c642db7852ae67a to your computer and use it in GitHub Desktop.
Perl Weekly Challenge 008
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";
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