Valid Perfect Square

How to check valid perfect square without sqrt (in-built Library function).

Given a positive integer, We have to write a code to returns true if it is a perfect square else false.

For solving this problem, we don’t have to use any built-in library function (such as sqrt).

For Example –

Example 1:

Input:  36

output: true

Example 2:

Input:  17

output: false

Example 3:

Input:  1

output: true

valid perfect square using binary search

In this tutorial, I am going to discuss multiple approaches to solve this problem.

Programming Video Tutorials

The simplest approach to solve this problem is by running a loop from 1 to n, where n is the input number. In each iteration do the square of a number and compare with the input number n. If it is equal then return true else return false.

Is there any better way to solve this problem? Yes let’s discuss it.

Valid Perfect Square without Sqrt – Java Code

We can solve this problem by using a property that the square root of a number lies between 2 to n/2.

It means if a number is less than 2 then simply return true. Otherwise run a loop from 2 to n/2. At each step do the square and compare with input number. If it’s equal to number then return true. If the square of a number is greater than the input number then return false.

Valid Perfect Square using Binary Search – Java Code

Given a number n, We know square root of n lies between 2 and n/2. Using this property we can solve this problem using Binary Search.

In this approach, we first calculate the mid using start and end variable. Then we check square of mid is equal to n. If it’s then it’s a valid perfect square.

Else if square of mid is greater than n then we assign mid-1 to end variable. If square of mid is smaller than n then we assign mid+1 to start.

The time complexity of this approach is O(logn).

Binary Search Java Code

Programming questions on Binary Search

Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.