Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ตรวจสอบว่าเลขจากการ Concatenate สองตัวเป็น Perfect Square หรือไม่ด้วย Python

โจทย์: กำหนดเลข x และ y Concatenate แล้วตรวจสอบว่าเป็น Perfect Square หรือไม่

ตัวอย่าง

x = 2, y = 89 → "289" = 17² → True

อัลกอริทึม

  1. แปลง x, y เป็น String Concatenate → Integer
  2. หาค่ารากที่สองแบบ Integer (int(sqrt))
  3. ตรวจสอบ sqrt² == เลขที่ได้

โค้ดตัวอย่าง

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))

Input / Output

Input: 2, 89
Output: True