Peter’s blog ✴ Week 105 ✴ 22 March 2021

THE WEEKLY CHALLENGE
Root and game

The Perl Camel

Task 1

Nth root

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 Wikipedia page.

Examples


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

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

Analysis

Why mess around? The easy method, mentioned on the Wiki page, is:

   ___
$k√ $N = e * ln($k / $N)

The Perl log function gives the log to the base e, where e - Euler's Number - is about 2.7182818284.

I am sorry that the 'Try it' feature is currently working very slowly or not at all owing to some issue with my web hosting provider.

Try it 

Try running the script with any input:



example: 3



example: 125

Script


#!/usr/bin/perl

# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

use v5.26;    # The Weekly Challenge - 2021-03-22
use utf8;     # Week 105 - task 1 - Nth root
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';
use Encode;

nth_root(5, 248832);
nth_root(5, 34);
nth_root(7, 60170087060757);
nth_root(0.5, 4);

sub nth_root {
    
    say qq[\nInput:  \$n = $_[0], \$k = $_[1]];
    say qq[Output: ] . sprintf('%.4f', 2.7182818284 ** (log($_[1]) / $_[0]));
}

3 lines of code
Completed after the closing date and not submitted to GitHub

Output from script


Input:  $n = 5, $k = 248832
Output: 12.0000

Input:  $n = 5, $k = 34
Output: 2.0244

Input:  $n = 7, $k = 60170087060757
Output: 93.0000

Input:  $n = 0.5, $k = 4
Output: 16.0000

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain