
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to check number is perfect square or not without sqrt function in Python
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
- Related Articles
- Check Perfect Square or Not
- Check if a number is perfect square without finding square root in C++
- Swift Program to Check if the given number is Perfect number or not
- Check whether the number formed by concatenating two numbers is a perfect square or not in Python
- Check if given number is perfect square in Python
- Swift Program to Check whether a number is a Perfect Cube or not
- Program to check a number is palindrome or not without help of a string in Python
- Program to check a number is ugly number or not in Python
- Program to check whether given number is Narcissistic number or not in Python
- Python Program to Check if a Number is a Perfect Number
- Check if a number in a list is perfect square using Python
- Python program to check if a number is Prime or not
- Python program to check credit card number is valid or not
- Python program to check a number n is weird or not
- C program to find if the given number is perfect number or not
