DEV Community

Simon Green
Simon Green

Posted on

Special zeros

Weekly Challenge 252

Each week Mohammad S. Anwar sends out The Weekly Challenge, a chance for all of us to come up with solutions to two weekly tasks. My solutions are written in
Python first, and then converted to Perl. It's a great way for us all to practice some coding.

Challenge, My solutions

Task 1: Special Numbers

Task

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.

My solution

Two pretty straight forward tasks this week, great way to get back into the new year. For this task, I create a variable length for the length of the list, and solution which starts with 0. Then it is simply a matter of iterating through the array as follows:

for pos in range(length):
    if length % (pos+1) == 0:
        solution += ints[pos] ** 2
Enter fullscreen mode Exit fullscreen mode

Examples

$ ./ch-1.py 1 2 3 4
21

$ ./ch-1.py 2 7 1 19 18 3
63
Enter fullscreen mode Exit fullscreen mode

Task 2: Unique Sum Zero

Task

You are given an integer, $n.

Write a script to find an array containing $n unique integers such that they add up to zero.

My solution

Looking at the example, I don't seem obvious how Mohammad come up with the numbers. Not to worry, I only need to come up with a solution that meets the criteria.

If $n is an even number, I can create pairs of an integer and its negative counterpart to add up to zero. If $n is odd, I can add a zero to ensure we have the correct number of integers.

solution = []
half = n // 2

if n % 2 == 1:
    solution = [0]

for i in range(half):
    # Add a pair of numbers
    solution.insert(0, -i-1)
    solution.append(i+1)

print(*solution, sep=', ')
Enter fullscreen mode Exit fullscreen mode

Examples

$ ./ch-2.py 5
-2, -1, 0, 1, 2

$ ./ch-2.py 3
-1, 0, 1

$ ./ch-2.py 1
0

$ ./ch-2.py 6
-3, -2, -1, 1, 2, 3
Enter fullscreen mode Exit fullscreen mode

Top comments (0)