Camel
Peter
Peter Campbell Smith

Root and game

Weekly challenge 105 — 22 March 2021

Week 105: 22 Mar 2021

Task 1

Task — 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.

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

I completed this challenge after the closing date
and it has not been submitted to GitHub

Output


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