From 2ba00d1fe2724412392b7c5c0dd05f5c661b00b9 Mon Sep 17 00:00:00 2001 From: Matthew Neleigh Date: Sun, 10 Oct 2021 17:02:41 -0400 Subject: new file: challenge-133/mattneleigh/perl/ch-1.pl --- challenge-133/mattneleigh/perl/ch-1.pl | 59 ++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100755 challenge-133/mattneleigh/perl/ch-1.pl 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); + } + +} + + + -- cgit