5 Best Ways to Check if a Given Number is a Perfect Square in Python

Rate this post

πŸ’‘ Problem Formulation: How do we determine whether a number is a perfect square using Python with maximal accuracy? A perfect square is an integer that is the square of another integer. For example, given the input number 16, the desired output is True because 16 is a square of 4.

Method 1: Using the Square Root

Calculating the square root and checking if it’s an integer is a straightforward way to verify if a number is a perfect square. Python’s math.sqrt() function is used, and then we verify if the square root is an integer using the is_integer() method.

Here’s an example:

import math

def is_perfect_square(num):
    sqrt = math.sqrt(num)
    return sqrt.is_integer()

print(is_perfect_square(16))

Output: True

This example defines a function is_perfect_square() that takes an integer as input, calculates its square root, and checks if the result is an integer, signaling that the original number is a perfect square.

Method 2: Using Exponentiation

In Python, the exponentiation operator (**), when used with 0.5 (which is equivalent to square root), can be another method to determine if a number is a perfect square. The process involves calculating the square root and then squaring it to check if it equals the original number.

Here’s an example:

def is_perfect_square(num):
    root = num ** 0.5
    return int(root + 0.5) ** 2 == num

print(is_perfect_square(16))

Output: True

This snippet takes advantage of the fact that squaring the rounded square root of a number should return the original number if it’s a perfect square.

Method 3: Using a While Loop

This method iteratively checks squares of numbers using a loop. Starting from 1, we square each number and compare it to the input until we find a perfect square or surpass the input number.

Here’s an example:

def is_perfect_square(num):
    i = 1
    while i*i <= num:
        if i*i == num:
            return True
        i += 1
    return False

print(is_perfect_square(16))

Output: True

This function iterates through natural numbers, squaring each and checking if it equals the input number. It stops when it either finds a match or when the square exceeds the input number, indicating that the input is not a perfect square.

Method 4: Using Binary Search

Binary search can efficiently determine if a number is a perfect square. This algorithm halves the search space each time by comparing the square of the middle element to the input number until it finds the square or exhausts the range.

Here’s an example:

def is_perfect_square(num):
    low, high = 1, num
    while low <= high:
        mid = (low + high) // 2
        square = mid * mid
        if square == num:
            return True
        elif square < num:
            low = mid + 1
        else:
            high = mid - 1
    return False

print(is_perfect_square(16))

Output: True

The code snippet uses binary search to quickly narrow down the possible integers whose square could be the input number, thereby checking for the perfect square efficiently.

Bonus One-Liner Method 5: Checking with Set Comprehension

Using set comprehension, we can check if a number is a perfect square in a one-liner. This is not the most efficient way, but it showcases Python’s powerful one-liner capabilities.

Here’s an example:

is_perfect_square = lambda num: num in {i*i for i in range(1, int(num**0.5)+1)}

print(is_perfect_square(16))

Output: True

This one-liner uses a set comprehension to create a set of squares up to the square root of the input number and checks if the input number is in that set.

Summary/Discussion

  • Method 1: Using the Square Root. This is the most straightforward and easily comprehensible method. It’s also quick for smaller numbers but may suffer from floating-point precision issues with very large numbers.
  • Method 2: Using Exponentiation. This method is similar to method 1 but avoids the possible floating-point precision issue by rounding the square root before squaring it. This could be less precise for numbers that are close to the square of a large integer.
  • Method 3: Using a While Loop. It’s simple and doesn’t rely on floating-point arithmetic, but it can be quite slow for large numbers, as it has a linear time complexity.
  • Method 4: Using Binary Search. It provides a balance between efficiency and ease of understanding, working well for large numbers due to its logarithmic time complexity.
  • Method 5: Checking with Set Comprehension. It demonstrates Python’s concise syntax but is not practical for very large numbers since it creates a set of all squares up to the square root, which can be memory-intensive.