You are given an array of integers, @ints. Write a script to find the sum of the squares of all special elements of the given array. An element $ints[i] (1-indexed) is called special if i divides n, i.e. n % i == 0, where n is the length of the given array.
Let n be the length of the array. Iterate i from 1 to n. Whenever n % i == 0, add the square of the (i - 1)-th (0-based) element to the running total. Time complexity is O(n) and space complexity is O(1).
#!/usr/bin/env perl
use v5.38;
use warnings;
use Type::Params -sigs;
use Types::Standard qw(ArrayRef Int);
use Test::More;
my $check_ints = signature( positional => [ ArrayRef [Int] ] );
sub sum_of_special_squares ($ints) {
($ints) = $check_ints->($ints);
my $n = scalar @{$ints};
my $sum = 0;
for my $i ( 1 .. $n ) {
$sum += $ints->[ $i - 1 ]**2 if $n % $i == 0;
}
return $sum;
}from collections.abc import Sequence
def sum_of_special_squares(ints: Sequence[int]) -> int:
"""Return the sum of squares of all special elements in ints.
An element at 1-based index ``i`` is special if ``i`` divides ``len(ints)``.
"""
n = len(ints)
return sum(ints[i - 1] ** 2 for i in range(1, n + 1) if n % i == 0)You are given an integer, $n. Write a script to find an array containing $n unique integers such that they add up to zero.
We can construct the array directly using symmetric pairs (i, -i) for i = 1 .. floor(n / 2). Every pair sums to zero and all elements are distinct. If n is odd, we append 0 to reach length n without changing the sum. Time and space complexity are both O(n).
#!/usr/bin/env perl
use v5.38;
use warnings;
use Type::Params -sigs;
use Types::Standard qw(Int);
use Test::More;
my $check_n = signature( positional => [Int] );
sub unique_sum_zero ($n) {
($n) = $check_n->($n);
die "n must be non-negative\n" if $n < 0;
my @result = map { $_, -$_ } ( 1 .. int( $n / 2 ) );
push @result, 0 if $n % 2 != 0;
return \@result;
}def unique_sum_zero(n: int) -> list[int]:
"""Return a list of n unique integers that add up to zero."""
if n < 0:
raise ValueError("n must be non-negative")
half = n // 2
result: list[int] = []
for i in range(1, half + 1):
result.extend((i, -i))
if n % 2 != 0:
result.append(0)
return result