Perl Weekly Challenge 105: Nth root

by Abigail

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.

Examples

Input: $N = 5, $k = 248832
Output: 12

Input: $N = 5, $k = 34
Output: 2.02

Discussion

This is pretty straightforward. The \(\text{Nth}\) root of \(k\), \(\sqrt[N]{k}\) is easily found by raising \(k\) to the power of \(\frac{1}{N}\):

\[k^\frac{1}{N}\]

This solves the issue for languages which allow exponentation where the exponent isn't an integer. Perl is one of these languages.

For languages which don't, we take the formula above; take the natural logarithm of it, and raise \({\bf e}\) to that:

\[k^\frac{1}{N} = {\bf e}^{\ln{k^\frac{1}{N}}} = {\bf e}^{\frac{\ln k}{N}}\]

This solves the problem for languages which have a log and an exp function.

Solutions

We are assuming the input consists of one or more lines — each line consisting of two numbers (separated by white space): \(N\), and \(k\). We will be outputting \(k^{\frac{1}{N}}\) for each line of input.

Perl

In Perl, we can solve this with what basically is a one-liner:

$_ = [split], say $$_ [1] ** (1 / $$_ [0]) while <>;

We take a line of input, split it on white space, then we raise the second number (\(k\)) to the power of the inverse of the first (\(N\)).

Find the full program on GitHub.

Pascal

Pascal does not allow us to raise numbers to a non-integer power, we we're taking the natural logarithm of \(k\), divide that by \(N\), and raise \({\bf e}\) to the result of that:

var N, k: double;

begin
    while not eof () do
    begin
        readln (N, k);
        writeln (exp (ln (k) / N) : 1 : 10);
    end
end.

Find the full program on GitHub.

Other languages

We also have solutions in AWK, bc, C, Fortran, Lua, Node.js, Python, Ruby, Scheme, and SQL, using one of the strategies explained above.


Please leave any comments as a GitHub issue.