diff options
| author | wanderdoc <wanderdoc@googlemail.com> | 2021-03-28 16:01:38 +0200 |
|---|---|---|
| committer | wanderdoc <wanderdoc@googlemail.com> | 2021-03-28 16:01:38 +0200 |
| commit | 0e275eccc7f233e0a312f3ec47b64f74450eba32 (patch) | |
| tree | ef3749a5891ecc0c365491ea19f8fa6de243d159 /challenge-105 | |
| parent | de95a289221eae06c7d2c6537102b4ed651448c2 (diff) | |
| download | perlweeklychallenge-club-0e275eccc7f233e0a312f3ec47b64f74450eba32.tar.gz perlweeklychallenge-club-0e275eccc7f233e0a312f3ec47b64f74450eba32.tar.bz2 perlweeklychallenge-club-0e275eccc7f233e0a312f3ec47b64f74450eba32.zip | |
Solution to task 1 challenge-105
Diffstat (limited to 'challenge-105')
| -rw-r--r-- | challenge-105/wanderdoc/perl/ch-1.pl | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/challenge-105/wanderdoc/perl/ch-1.pl b/challenge-105/wanderdoc/perl/ch-1.pl new file mode 100644 index 0000000000..8eb943262b --- /dev/null +++ b/challenge-105/wanderdoc/perl/ch-1.pl @@ -0,0 +1,46 @@ +#!perl +use strict; +use warnings FATAL => qw(all); + +=prompt +You are given positive numbers $N and $k. Write a script to find out the $Nth root of $k. +Example +Input: $N = 5, $k = 248832 Output: 12 +Input: $N = 5, $k = 34 Output: 2.02 +=cut + + + + + + + +use Test::More; +use List::Util qw(reduce); + +sub nthroot # newton algorithm +{ + my ( $n, $k, $precision ) = @_; + + $precision //= 5; + + my $x0 = $k / $n; + my $x1; + + while (1) + { + $x1 = (1 / $n) * + ( ( $n - 1 ) * $x0 + $k / ( reduce { $a * $b } ($x0) x ($n - 1) ) ); + last if sprintf("%.${precision}f", $x0) == sprintf("%.${precision}f", $x1); + $x0 = $x1; + } + return sprintf("%.${precision}f", $x1) + 0; +} + + +is(nthroot(5, 248832), 12, 'Example 1'); +is(nthroot(5, 34, 2), 2.02, 'Example 2'); +is(nthroot(2, 2, 8), 1.41421356, 'Example 3'); +is(nthroot(5, 222), 2.94626, 'Example 4'); +is(nthroot(123, 987), 1.05766, 'Example 5'); +done_testing();
\ No newline at end of file |
