PWC 175

PWC 175

Challenge 1 -- Last Sunday

Challenge 1 asks us to find the last Sunday of every month in a particular year, say 2022.

This is easy to do in Perl thanks to the Date::Manip suite of modules, which bristles with options, including a straightforward way to do this. The specific module useful here is Date::Manip::Recur

With this module it's as easy as saying:

$date_recur_object -> parse("last Sunday of every month in 2022");

which is exactly what I do.

In Raku, it's a bit more difficult, but still easy via Raku's excellent and well-documented built-in Date objects. Pretty much a matter of looping through the last 10 days of each month, picking up the Sundays in that stretch, and then keeping the last Sunday.

Julia is similar to Raku in its Dates handling, except that the Dates are not built-in, but a short library call away. I could have translated my Raku script line-for-line to Julia, but I have the minor difference that I used multiple dispatch in Raku and a single function in Julia.

Here is my Perl 5 script.

Here is my Raku script.

Here is my Julia script. 


Challenge 2

Challenge 2 is again a number-theory exercise. The task is to find the first 20 perfect totient numbers. I had never heard of totients before this exercise, but apparently they are quite a useful concept, used in RSA cryptography for example. The totient function of a positive integer n counts the number of positive integers less than n that are relatively prime to n, i.e., do not have a common factor with n except for 1. To get the perfect totient numbers, we iteratively compute the totients for each candidate n (i.e., totient(n), then totient(totient(n)), ...) and at each stage we add the answer to the sum of the results from previous iterations, stopping when the iteratively-computed totient is 1. A number is a perfect totient number  when the result of this calculation equals the number itself.

The related OEIS page helpfully gives a Perl script to compute the perfect totient numbers. This in turn points to the extensive and useful ntheory library aka Math::Prime::Util and its "euler_phi" function (another name for the totient function).

This is the approach I followed. I used it in Raku too using Inline::Perl 5 to call the Perl 5 library. The Primes module in Julia too has a totient function, so it is easy to apply the same logic in Julia.

Here is my Perl 5 solution

Here is my Raku solution

Here is my Julia solution

Comments

Popular posts from this blog

PWC 258

PWC 253

PWC 249