In Python, if you have to check whether a given number is a perfect square or not, then you are at the right place. In this article we will cover two different approach for doing this.
These kinds of simple coding problems are usually asked in interviews to see how well the interviewee can think through the process and come up with a reliable logic.
Given a number, check if it is a valid perfect square, given the condition that no built-in functions such as sqrt
should be used.
Note: Before looking into the solution, it is highly recommended to figure out the logic on your own.
Sample input: 25
Sample output: True
Sample input: 23
Sample output: False
Approach 1:
-
This is similar to the binary search wherein 'left' and 'right' variables are assigned to 0 and the number respectively.
-
The 'left' variable is checked for being less than or equal to the 'right' variable and then a 'mid' value is defined.
-
This 'mid' value is squared and checked to be less than, greater than or equal to the 'num'. Based on this, True or False is returned.
def is_perfect_square(num) :
left, right = 0, num
while left <= right:
mid = (left + right) // 2
if mid**2 < num:
left = mid + 1
elif mid**2 > num:
right = mid - 1
else:
return True
return False
print("25 is a valid perfect square")
print(is_perfect_square(25))
print("\n")
print("23 is a valid perfect square")
print(is_perfect_square(23))
25 is a valid perfect square
True
23 is a valid perfect square
False
Let us look at another approach:
This is a simple one-liner that checks if the 'num' raised to the power of 0.5, i.e the square root of the number is equal to a 'temp' variable.
def is_perfect_square(num):
temp = num**(0.5)
return (temp//1)==temp
print("25 is a valid perfect square")
print(is_perfect_square(25))
print("\n")
print("23 is a valid perfect square")
print(is_perfect_square(23))
25 is a valid perfect square
True
23 is a valid perfect square
False
Conclusion
In this post, we saw one of the coding questions that are usually asked in interviews. Let us know how you would approach this problem in the comment section below. Happy coding!
You may also like: