Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chương trình Python kiểm tra hai số Amicable (Số thân thiết)

Số thân thiết (Amicable numbers) là hai số khác nhau mà tổng ước số thực của mỗi số bằng số kia. Kiểm tra hai số amicable, định nghĩa phương thức lặp số, dùng modulus. Phương thức khác gọi hàm trước xác định amicable.

Minh họa:

Ví dụ

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

Kết quả

The numbers are : 220 288
The given numbers are not amicable in nature

Giải thích

  • Phương thức 'divided_sum_val' nhận integer tham số.
  • Dùng 'for' lặp giá trị kiểm tra tính chia hết.
  • Nếu iterator bằng giá trị chia iterator, tăng iterator.
  • Ngược lại, cộng toàn bộ số chia.
  • Phương thức 'check_amicable' nhận hai số.
  • Gọi 'divided_sum_val' trả True/False theo giá trị tính.
  • Hai số định nghĩa hiển thị console.
  • Gọi phương thức truyền hai số.
  • Dựa output hiển thị thông điệp.