Programming challenges

The Weekly Challenge - 252 (January 15th 2024)

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 $int[i] of @ints is called special if i divides n, i.e. n % i == 0. Where n is the length of the given array. Also the array is 1-indexed for the task.

Example 1

Input: 1,2,3,4
Output: 21

Example 2

Input:  2,7,1,19,18,3
Output: 63

Solutions

We write three solutions this week. The first in pure Perl, the second using the library Math::Prime::Util to do the “heavy lifting”, the third adds in List::Util.

In the pure perl version we loop through each index and IF the index is a divisor we add the square to the running total. Note we use || to replace unless within a postfix for. Could use a grep to do the filtering but it’s slower.

The library version, replaces the filtering with retrieving the divisors using Math::Prime::Util. This greatly speeds up the code for larger lists.

I looked at List::Util‘s sum0 – but because of the need for a map and function calls, just using an single variable to total the
values runs about 25% faster. I’ve always wondered why with many of the functions in Util::List why sum0, prod can’t take a call-back like map to improve performance in these cases.

252_1_special_numbers.pl - perl

sub special_numbers {
my $t=0;
(@_%$_) || ($t+=$_[$_-1]**2) for 1..@_;
$t
}

use Math::Prime::util qw(divisors);

sub special_numbers_prime {
my $t=0;
$t+=$_[$_-1]**2 divisors @_;
$t
}

use List::Util qw(sum0);

sub special_numbers_prime_list_util {
sum0 map { $_[$_-1]**2 } divisors @_
}

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.

Example 1

Input: 1
Output: 0

Example 2

Input: 2
Output: -1, 1

Example 3

Input: 3
Output: 0, -1, 1

Example 4

Input: 5
Output: -7, 0, 1, 2, 4

Solution

Rarely is task 2 easier to code than task 1 – but in this case it is.

We note that for even n we can just choose a list containing -i & i.

We note that for one n we can just do the same and add a 0.

252_2_unique_sum_zero.pl - perl

sub unique_sum_zero {
($_[0]%2) ? (0) : (), map { -$_,$_ } 1 .. $_[0]/2
}

About The Weekly Challenge

The weekly challenge was set up Mohammad Anwar approximately 5 years ago - each Monday two problems are set for the "team" to solve.

These are posted at: