The Weekly Challenge 252

Special Numbers & Unique Sum Zero

Official Challenge • Solutions on GitHub

Task 1: Special Numbers

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.

Examples

Input: @ints = (1, 2, 3, 4) Output: 21 # Special indices: 1, 2, 4 (all divide 4) # 1^2 + 2^2 + 4^2 = 1 + 4 + 16 = 21 Input: @ints = (2, 7, 1, 19, 18, 3) Output: 63 # Special indices: 1, 2, 3, 6 (all divide 6) # 2^2 + 7^2 + 1^2 + 3^2 = 4 + 49 + 1 + 9 = 63

Logic

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).

Perl Solution

#!/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;
}

Python Solution

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)

Task 2: Unique Sum Zero

You are given an integer, $n. Write a script to find an array containing $n unique integers such that they add up to zero.

Examples

Input: $n = 5 Output: (1, -1, 2, -2, 0) Input: $n = 3 Output: (1, -1, 0) Input: $n = 1 Output: (0)

Logic

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).

Perl Solution

#!/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;
}

Python Solution

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