diff options
| author | Jörg Sommrey <28217714+jo-37@users.noreply.github.com> | 2021-10-04 23:08:50 +0200 |
|---|---|---|
| committer | Jörg Sommrey <28217714+jo-37@users.noreply.github.com> | 2021-10-08 16:59:09 +0200 |
| commit | d005bc0a72119706aad5a5482369eb079e773332 (patch) | |
| tree | 4913d07f884a273dc9e094dce910aec319f18e81 | |
| parent | fdcf783f36a82f44570fdd2ee49c0fc7ce14f110 (diff) | |
| download | perlweeklychallenge-club-d005bc0a72119706aad5a5482369eb079e773332.tar.gz perlweeklychallenge-club-d005bc0a72119706aad5a5482369eb079e773332.tar.bz2 perlweeklychallenge-club-d005bc0a72119706aad5a5482369eb079e773332.zip | |
Solution to task 1
| -rwxr-xr-x | challenge-133/jo-37/perl/ch-1.pl | 72 |
1 files changed, 72 insertions, 0 deletions
diff --git a/challenge-133/jo-37/perl/ch-1.pl b/challenge-133/jo-37/perl/ch-1.pl new file mode 100755 index 0000000000..263116b17b --- /dev/null +++ b/challenge-133/jo-37/perl/ch-1.pl @@ -0,0 +1,72 @@ +#!/usr/bin/perl -s + +use v5.16; +use integer; +use Test2::V0; +use experimental 'signatures'; + +our ($tests, $examples); + +run_tests() if $tests || $examples; # does not return + +die <<EOS unless @ARGV; +usage: $0 [-examples] [-tests] [N] + +-examples + run the examples from the challenge + +-tests + run some tests + +N + calculate integer square root of N + +EOS + + +### Input and Output + +say int_sqrt(shift); + + +### Implementation + +# Following the formulae in +# https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division + +sub int_sqrt ($n) { + my $prev = $n; + while () { + my $next = ($prev + $n / $prev) / 2; + return $prev if $next >= $prev; + $prev = $next; + } +} + + +### Examples and tests + +use Math::Prime::Util (); + +sub run_tests { + SKIP: { + skip "examples" unless $examples; + + is int_sqrt(10), 3, 'example 1'; + is int_sqrt(27), 5, 'example 2'; + is int_sqrt(85), 9, 'example 3'; + is int_sqrt(101), 10, 'example 4'; + } + + SKIP: { + skip "tests" unless $tests; + + my $mpu_sqrtint = \&Math::Prime::Util::sqrtint; + grep { + int_sqrt($_) != $mpu_sqrtint->($_) and !fail "$_ failed"; + } 1 .. 1e5 or pass 'cross check'; + } + + done_testing; + exit; +} |
