Program to check number is perfect square or not without sqrt function in Python

PythonServer Side ProgrammingProgramming

Suppose we have a number n, we have to check whether n is a perfect square number or not. A perfect square number k can be represented as k = a * a for some integer a. We have to solve this without using built-in square root function.

So, if the input is like n = 121, then the output will be True because 121 = 11*11.

To solve this, we will follow these steps −

  • if n is same as 0 or n is same as 1, then

    • return True

  • start := 2

  • stop := floor of n / 2

  • while start <= stop, do

    • temp := a list of all numbers from start to stop

    • k := middle element of temp

    • k_squared := k * k

    • if k_squared is same as n, then

      • return True

    • if k_squared > n, then

      • start := temp[0]

      • stop := k - 1

    • otherwise,

      • start := k + 1

      • stop := last element of temp

  • return False

Example

Let us see the following implementation to get better understanding

def solve(n):
   if n == 0 or n == 1:
      return True
   start = 2
   stop = n // 2
   while start <= stop:
      temp = range(start, stop + 1)

   k = temp[len(temp) // 2]
   k_squared = k * k 

   if k_squared == n:
      return True

   if k_squared > n:
      start = temp[0]
      stop = k - 1
   else:
      start = k + 1
      stop = temp[-1]

   return False

n = 121
print(solve(n))

Input

121

Output

True
raja
Updated on 11-Oct-2021 06:43:44

Advertisements