-
-
Save jbfeldman/1aa84209bab44c14d0566ff5fdc47ea5 to your computer and use it in GitHub Desktop.
Solves @Casidoos 11-23-2020 challenge: find if an integer has a square root
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def is_square(n, upper, lower=0): | |
#edge case | |
if n == 1: | |
return True | |
#if exhausted all possibilities | |
if upper - lower < 2 and lower**2 != n and upper != n: | |
return False | |
guess = ((upper - lower) // 2) + lower | |
guess_square = guess ** 2 | |
if guess_square == n: | |
return True | |
#recurse on lower half | |
elif guess_square > n: | |
return is_square(n, upper=guess, lower=lower) | |
#recurse on higher half | |
elif guess_square < n: | |
return is_square(n, upper=upper, lower=guess) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment