aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMohammad S Anwar <Mohammad.Anwar@yahoo.com>2021-10-10 22:10:12 +0100
committerGitHub <noreply@github.com>2021-10-10 22:10:12 +0100
commitcc57c183c2f6329047a86e0c39476e9acb4dc5bf (patch)
tree80ca319b4398f3f3d2aaed867ee8b723b1dcc3a0
parent60b0d28bad02216adb4810e545678ce32e9881cb (diff)
parent2ba00d1fe2724412392b7c5c0dd05f5c661b00b9 (diff)
downloadperlweeklychallenge-club-cc57c183c2f6329047a86e0c39476e9acb4dc5bf.tar.gz
perlweeklychallenge-club-cc57c183c2f6329047a86e0c39476e9acb4dc5bf.tar.bz2
perlweeklychallenge-club-cc57c183c2f6329047a86e0c39476e9acb4dc5bf.zip
Merge pull request #5001 from mattneleigh/pwc133
new file: challenge-133/mattneleigh/perl/ch-1.pl
-rwxr-xr-xchallenge-133/mattneleigh/perl/ch-1.pl59
1 files changed, 59 insertions, 0 deletions
diff --git a/challenge-133/mattneleigh/perl/ch-1.pl b/challenge-133/mattneleigh/perl/ch-1.pl
new file mode 100755
index 0000000000..eeb32c03d6
--- /dev/null
+++ b/challenge-133/mattneleigh/perl/ch-1.pl
@@ -0,0 +1,59 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+
+################################################################################
+# Begin main execution
+################################################################################
+
+my @numbers = (10, 27, 85, 101);
+my $number;
+
+foreach $number (@numbers){
+ printf(
+ "Input: \$N = %d\nOutput: %d\n\n",
+ $number,
+ isqrt($number)
+ );
+}
+
+exit(0);
+################################################################################
+# End main execution; subroutines follow
+################################################################################
+
+
+################################################################################
+# Calculate the integer square root (that is to say, the largest integer less
+# than or equal to the square root) of a supplied integer
+# Takes one argument:
+# * A positive integer
+# Returns on success:
+# * The integer square root of the supplied integer
+# Returns on error:
+# * undef if a negative number is supplied
+# Lazily adapted from an algorithm described at
+# https://en.wikipedia.org/wiki/Integer_square_root
+################################################################################
+sub isqrt{
+ my $n = int(shift());
+
+ my $small_candidate;
+ my $large_candidate;
+
+ return(undef) if($n < 0);
+ return($n) if($n < 2);
+
+ $small_candidate = isqrt($n >> 2) << 1;
+ $large_candidate = $small_candidate + 1;
+ if(($large_candidate * $large_candidate) > $n){
+ return($small_candidate);
+ } else{
+ return($large_candidate);
+ }
+
+}
+
+
+