Here we are with TASK #1 from the Perl Weekly Challenge #105. Enjoy!

The challenge

You are given positive numbers $N and $k. Write a script to find out the $Nth root of $k. For more information, please take a look at the wiki page.

The questions

The first and foremost question that popped in my mind was… am I reading this challenge right? Looking at the wiki page just got me more confused.

But well, it’s clearly stated that the two numbers are positive, and I definitely remember that extracting the $k$-th root of a number $N$ is the same as elevating that number to $k^{-1}$, ending with $N^{k^{-1}}$… so why not?!?

The solution

This solution allowed me discover that the exponentiation operator in Perl is right associative. Which is actually very good in this case, as the solution can be written almost completely in terms of exponentiations, just like the formula above:

sub nth_root ($N, $k) { return $N ** $k ** -1 }

Come to think about it, the operator is probably right-associative exactly because in this way it matches how stuff like this would be laid out. Just like the formula above, I mean.

I said almost because we still have to use the - sign in front of the 1. Let’s say that it’s up to you to think of it as just a convention to write an integer, or actually think that 1 is the star and -1 is just expressed in terms of it by using a subtraction operation from an imaginary 0.

Well, time for the whole code:

#!/usr/bin/env perl
use 5.024;
use warnings;
use experimental 'signatures';
no warnings 'experimental::signatures';

sub nth_root ($N, $k) { return $N ** $k ** -1 }

my $N_ = shift || 34;
my $k_ = shift || 5;
say nth_root($N_, $k_);

Stay safe folks!