aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLubos Kolouch <lubos@kolouch.net>2021-10-09 12:31:16 +0200
committerLubos Kolouch <lubos@kolouch.net>2021-10-09 12:31:16 +0200
commit136fb62d1de876d28a11733c8a8bd2d74f6e535b (patch)
treea9c083f643a7241df617386659dfd1d946b7573e
parent4cd8d62dd835b0e16e39aae2169896ec58796b51 (diff)
downloadperlweeklychallenge-club-136fb62d1de876d28a11733c8a8bd2d74f6e535b.tar.gz
perlweeklychallenge-club-136fb62d1de876d28a11733c8a8bd2d74f6e535b.tar.bz2
perlweeklychallenge-club-136fb62d1de876d28a11733c8a8bd2d74f6e535b.zip
Challenge 133 Task 1 Perl Python
-rw-r--r--challenge-133/lubos-kolouch/perl/ch-1.pl36
-rw-r--r--challenge-133/lubos-kolouch/python/ch-1.py28
2 files changed, 64 insertions, 0 deletions
diff --git a/challenge-133/lubos-kolouch/perl/ch-1.pl b/challenge-133/lubos-kolouch/perl/ch-1.pl
new file mode 100644
index 0000000000..4381d74d4e
--- /dev/null
+++ b/challenge-133/lubos-kolouch/perl/ch-1.pl
@@ -0,0 +1,36 @@
+use strict;
+use warnings;
+
+sub get_square_root {
+ my ( $what, $low, $high ) = @_;
+
+ $high //= $what;
+ $low //= 0;
+
+ my $middle = int( ( $high + $low ) / 2 );
+ my $incr_middle = $middle + 1;
+
+ # halve the interval
+
+ if ( ( $middle * $middle <= $what ) and ( $incr_middle * $incr_middle >= $what ) ) {
+ return $middle;
+ }
+
+ if ( $middle * $middle > $what ) {
+ $middle = get_square_root( $what, $low, $middle );
+ }
+ else {
+ $middle = get_square_root( $what, $middle, $high );
+ }
+
+ return $middle;
+}
+
+use Test::More;
+
+is( get_square_root(10), 3 );
+is( get_square_root(27), 5 );
+is( get_square_root(85), 9 );
+is( get_square_root(101), 10 );
+
+done_testing;
diff --git a/challenge-133/lubos-kolouch/python/ch-1.py b/challenge-133/lubos-kolouch/python/ch-1.py
new file mode 100644
index 0000000000..41c973def1
--- /dev/null
+++ b/challenge-133/lubos-kolouch/python/ch-1.py
@@ -0,0 +1,28 @@
+""" The Weekly Challenge 133 Task 1 """
+
+
+def get_square_root(what: int, low: int = 0, high: int = 0):
+ """ Calculate the square root using interval halving"""
+
+ if not high:
+ high = what
+
+ middle = int((high + low) / 2)
+ incr_middle = middle + 1
+
+ if middle * middle <= what <= incr_middle * incr_middle:
+ return middle
+
+ if middle * middle > what:
+ middle = get_square_root(what, low, middle)
+
+ else:
+ middle = get_square_root(what, middle, high)
+
+ return middle
+
+
+assert get_square_root(10) == 3
+assert get_square_root(27) == 5
+assert get_square_root(85) == 9
+assert get_square_root(101) == 10