Given a positive number, check if it is a perfect square without using any built-in library function. A perfect square is a number that is the square of an integer.

For example,

Input: n = 25
Output: true
Explanation: 25 is a perfect square since it can be written as 5×5.
 
 
Input: n = 20
Output: false
Explanation: 20 is not the product of an integer with itself.

1. Using Perfect Square Property

Every perfect square satisfies the property that it is the sum of the odd numbers starting with one. For example,

1 = 1
4 = 1 + 3
9 = 1 + 3 + 5
16 = 1 + 3 + 5 + 7
25 = 1 + 3 + 5 + 7 + 9

n = 1 + 3 + 5 + … + (2*n-1)

We can make use of this property to determine if a number n is a perfect square or not. The idea is to repeatedly subtract odd numbers from n, starting from 1, until it becomes 0 or negative. If the value reaches 0 at some point, we can say that the number is a perfect square. However, if the value becomes negative without reaching 0, the number cannot be a perfect square. This is demonstrated below in C++, Java, and Python.

C++


Download  Run Code

Output:

true

Java


Download  Run Code

Output:

true

Python


Download  Run Code

Output:

True

The time complexity of the above procedure is O(n) and requires constant extra space, where n is the given number.

2. Using Binary Search

We can improve the time complexity of the solution to O(log(n)) by using a binary search algorithm. The idea is to start with the search space [low, high] = [0, n] and try to find a mid value that satisfies the condition mid × mid == n. Based on a comparison result between n and mid × mid, the procedure will increment low, decrement high, or return true if n is the product of mid with itself.

Here’s the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Output:

true

Java


Download  Run Code

Output:

true

Python


Download  Run Code

Output:

True

3. Using Newton’s Method

Finally, we can use Newton’s method to compute square roots. The mathematical logic behind Newton’s method is outside the scope of this article. The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

true

Java


Download  Run Code

Output:

true

Python


Download  Run Code

Output:

True