diff options
| author | Mohammad S Anwar <Mohammad.Anwar@yahoo.com> | 2021-10-10 22:10:12 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2021-10-10 22:10:12 +0100 |
| commit | cc57c183c2f6329047a86e0c39476e9acb4dc5bf (patch) | |
| tree | 80ca319b4398f3f3d2aaed867ee8b723b1dcc3a0 | |
| parent | 60b0d28bad02216adb4810e545678ce32e9881cb (diff) | |
| parent | 2ba00d1fe2724412392b7c5c0dd05f5c661b00b9 (diff) | |
| download | perlweeklychallenge-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-x | challenge-133/mattneleigh/perl/ch-1.pl | 59 |
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); + } + +} + + + |
