Task1
We check if the array's length is divisible by index+1, if so we square the array at that index, at last we sum the whole acquired array:
#!usr/bin/env perl
use strict;
use warnings;
use List::Util qw(sum0);
sub special_numbers{
my ($arr) = @_;
sum0 map{($arr->[$_] ** 2) if @$arr % ($_+1) == 0} 0..$#$arr;
}
printf "%d\n",special_numbers([1,2,3,4]);
printf "%d\n",special_numbers([2,7,1,19,18,3]);
Task2
Starting from 1 to the half of the given number, we keep pushing the number and its negation to an array, then if the given number is odd, we push an extra zero at the end:
#!usr/bin/env perl
use strict;
use warnings;
use Data::Show;
sub unique_sum_zero{
my ($n,@ret) = @_;
foreach(1..$n/2){
push(@ret,$_,-$_);
}
$n % 2 ? (@ret,0) : @ret;
}
print show unique_sum_zero(5);
print show unique_sum_zero(3);
print show unique_sum_zero(1);
No comments:
Post a Comment