You are given positive numbers
$N
and$k
.Write a script to find out the
$N
th root of$k
. For more information, please take a look at the wiki page.
Input: $N = 5, $k = 248832
Output: 12
Input: $N = 5, $k = 34
Output: 2.02
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.
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.
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 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.