Amicable Numbers คือคู่เลขที่ผลรวมตัวหารของแต่ละจำนวน (ไม่รวมตัวมันเอง) เท่ากับอีกจำนวนหนึ่ง
ตัวอย่างโค้ด
import math
def divided_sum_val(my_val):
res = 0
for i in range(2, int(math.sqrt(my_val)) + 1):
if (my_val % i == 0):
if (i == int(my_val / i)):
res = res + i
else:
res = res + (i + int(my_val / i))
return (res + 1)
def check_amicable(x, y):
if (divided_sum_val(x) != y):
return False
return (divided_sum_val(y) == x)
first_num = 220
second_num = 288
print("The numbers are :")
print(first_num)
print(second_num)
if (check_amicable(first_num, second_num)):
print("The given numbers are amicable in nature")
else:
print("The given numbers are not amicable in nature")
ผลลัพธ์
The numbers are : 220 288 The given numbers are not amicable in nature
คำอธิบาย
- divided_sum_val: หาผลรวมตัวหาร (รวม 1) โดยวนจนถึงรากที่สอง
- check_amicable: ตรวจสอบเงื่อนไข Amicable ทั้งสองทาง
- 220 และ 284 เป็นคู่ Amicable จริง (ตัวอย่างใช้ 288 จึงเป็น False)