Check whether the number can be made perfect square after adding 1 in Python

Given a number n, we need to check whether adding 1 to it results in a perfect square. A perfect square is a number that can be expressed as the product of an integer with itself (like 4 = 2², 9 = 3², 16 = 4²).

For example, if n = 288, then n + 1 = 289, and 289 = 17², so the answer is True.

Algorithm

To solve this problem, we follow these steps ?

  • Calculate res_num = n + 1
  • Find sqrt_val = integer part of square root of res_num
  • If sqrt_val × sqrt_val equals res_num, return True
  • Otherwise, return False

Example

Here's the implementation of the algorithm ?

from math import sqrt

def solve(n):
    res_num = n + 1
    sqrt_val = int(sqrt(res_num))
    
    if sqrt_val * sqrt_val == res_num:
        return True
    return False

# Test with example
n = 288
print(f"Input: {n}")
print(f"Output: {solve(n)}")
print(f"Verification: {n} + 1 = {n + 1} = {int(sqrt(n + 1))}²")
Input: 288
Output: True
Verification: 288 + 1 = 289 = 17²

Testing Additional Cases

Let's test with more examples to understand the pattern ?

from math import sqrt

def solve(n):
    res_num = n + 1
    sqrt_val = int(sqrt(res_num))
    
    if sqrt_val * sqrt_val == res_num:
        return True
    return False

# Test multiple cases
test_cases = [8, 15, 24, 35, 48, 63, 80]

for n in test_cases:
    result = solve(n)
    if result:
        sqrt_result = int(sqrt(n + 1))
        print(f"n = {n}: {result} ({n} + 1 = {n + 1} = {sqrt_result}²)")
    else:
        print(f"n = {n}: {result}")
n = 8: True (8 + 1 = 9 = 3²)
n = 15: True (15 + 1 = 16 = 4²)
n = 24: True (24 + 1 = 25 = 5²)
n = 35: True (35 + 1 = 36 = 6²)
n = 48: True (48 + 1 = 49 = 7²)
n = 63: True (63 + 1 = 64 = 8²)
n = 80: True (80 + 1 = 81 = 9²)

How It Works

The algorithm works by checking if n + 1 is a perfect square. We take the square root of (n + 1), convert it to an integer to remove any decimal part, then square it back. If the result equals (n + 1), then (n + 1) is indeed a perfect square.

For n = 288:

  • res_num = 288 + 1 = 289
  • sqrt_val = int(?289) = int(17.0) = 17
  • 17 × 17 = 289, which equals res_num
  • Therefore, return True

Conclusion

This solution efficiently checks if adding 1 to a number creates a perfect square by calculating the integer square root and verifying the result. The time complexity is O(1) since we only perform basic mathematical operations.

Updated on: 2026-03-25T14:41:20+05:30

622 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements