Re: Factor

Factor: the language, the theory, and the practice.

Special Numbers

Monday, January 15, 2024

#math

Lots of numbers are special in various definitions of specialness. This often forms the basis of different programming challenges. In the case of the most recent Perl Weekly Challenge #252, the problem statement declares that a number is “special” in this way:

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.

And it gives two examples, which we can use as test cases later when we solve this in Factor.

Spoiler Alert: This weekly challenge deadline is due in a few days from now (on January 21, 2024 at 23:59). This blog post provides some solutions to this challenge. Please don’t read on if you intend to complete the challenge on your own.

Solution

Let’s find the special indices – which are just the divisors of the length of the input sequence – and then take the elements at those special indices:

: special-numbers ( ints -- ints' )
    [ length divisors 1 v-n ] [ nths ] bi ;

And so, we can solve this problem for both provided examples:

{ 21 } [ { 1 2 3 4 } special-numbers sum-of-squares ] unit-test

{ 63 } [ { 2 7 1 19 18 3 } special-numbers sum-of-squares ] unit-test

And a “script”, if we wanted to take input from the command-line, as requested:

MAIN: [
    [ readln ] [
        split-words harvest [ string>number ] map
        dup special-numbers sum-of-squares
        "%u => %u\n" printf
    ] while*
]