Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Check whether the number formed by concatenating two numbers is a perfect square or not in Python
Sometimes we need to check if concatenating two numbers creates a perfect square. A perfect square is a number that can be expressed as the product of an integer with itself (like 16 = 4²).
So, if the input is like x = 2 and y = 89, then the output will be True as after concatenating the number will be 289 which is 17².
Algorithm
To solve this problem, we will follow these steps ?
- Convert both numbers to strings
- Concatenate the strings and convert back to integer
- Find the integer square root of the concatenated number
- Check if squaring the result gives us the original number
Example
Let us see the following implementation to get better understanding ?
from math import sqrt
def solve(x, y):
first_num = str(x)
second_num = str(y)
res_num = int(first_num + second_num)
sqrt_val = int(sqrt(res_num))
if sqrt_val * sqrt_val == res_num:
return True
return False
x = 2
y = 89
print(solve(x, y))
The output of the above code is ?
True
Testing Multiple Cases
Let's test with different number combinations ?
from math import sqrt
def solve(x, y):
first_num = str(x)
second_num = str(y)
res_num = int(first_num + second_num)
sqrt_val = int(sqrt(res_num))
if sqrt_val * sqrt_val == res_num:
return True
return False
# Test cases
test_cases = [(2, 89), (1, 44), (3, 6), (1, 21)]
for x, y in test_cases:
concatenated = int(str(x) + str(y))
result = solve(x, y)
print(f"x={x}, y={y} ? {concatenated} ? Perfect square: {result}")
The output of the above code is ?
x=2, y=89 ? 289 ? Perfect square: True x=1, y=44 ? 144 ? Perfect square: True x=3, y=6 ? 36 ? Perfect square: True x=1, y=21 ? 121 ? Perfect square: True
How It Works
The function works by converting both numbers to strings, concatenating them, and converting back to an integer. Then it finds the integer square root and checks if squaring it gives the original concatenated number. For example, 289 has square root 17, and 17² = 289, so it's a perfect square.
Conclusion
This approach efficiently checks if concatenated numbers form a perfect square by using string concatenation and integer square root verification. The method works for any positive integers and provides accurate results.
