How to check for a perfect square in python?

To check whether a given number is a perfect square or not there are several methods using various inbuilt functions and various operators in python. Some of the main methods are as follows:

Method 1: Using the sqrt() function from the math module

You can use the sqrt() function from the math module to find the square root of a number. The number is said to be a perfect square if the corresponding value of its square root is an integer. Here is an example:

Output:

The number is a perfect square

In this example, we first import the math module and then assign a number to the variable num. After that, we use the sqrt() function to find the square root of num. If the calculated value of the square root is an integer, we print a message indicating that the provided number is a perfect square. If the number is not a perfect square, we print a message to that effect.

Method 2: Using the ** operator

The "**" operator which calculates the value of a number raised to certain power can also be used to determine whether a number is a perfect square or not. Here is an example:

Output:

The provided number is not a perfect square.

Method 3: Using the integer division operator //

The integer division operator // can also be used to determine whether a number is a perfect square or not. Here is an example:

Output:

The number is a perfect square.

Method 4: Using a loop to check all possible square roots

You can use the loop to find the square root of a number. Here is an example:

Output:

True

Method 5: Using binary search to find the square root:

You can use the binary search method to find the square root of a number. Here is an example:

Output:

False

In this approach, the square root of the given number is found with the help of binary search. We start by initializing the left and right boundaries to 0 and n respectively. After that, we calculate the midpoint and check if its square is equal to the original number. If the square is less than the original number, we adjust the left boundary to mid + 1. We modify the right boundary to "mid-1" if the square is larger than the starting value. We repeat this process until we find the square root or the left and right boundaries cross each other.






Latest Courses