其他分享
首页 > 其他分享> > Problem 21

Problem 21

作者:互联网

Problem 21

https://projecteuler.net/problem=21

Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).

If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers.

如果a的因子之和等于b,b的因子之和等于a,并且a不等于b,那么a和b称为亲和数。

For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.

Evaluate the sum of all the amicable numbers under 10000.

计算10000以下的所有亲和数之和。

import time


def is_amicable_number(num1, num2, divisors_num1, divisors_num2):
    if sum(divisors_num1) != num2:
        return False
    if sum(divisors_num2) != num1:
        return False
    return True


def find_divisors(num):
    divisors = []
    for i in range(1, num//2+1):
        if num % i == 0:
            divisors.append(i)
    return divisors


start_time = time.ctime()
amicable_numbers = []
for x in range(1, 10001):
    x_divisors = find_divisors(x)
    for y in range(x//2, x):
        y_divisors = find_divisors(y)
        print('Searching for amicable numbers({x}?{y})...'.format(x=x, y=y))
        if is_amicable_number(x, y, x_divisors, y_divisors):
            print('Amicable numbers:', x, ':', y)
            amicable_numbers.append([x, y])
end_time = time.ctime()
print(start_time)
print(end_time)
print(amicable_numbers)
tot = 0
for i in amicable_numbers:
    tot += sum(i)
print(tot)

 

结果:

10000以下的亲和数:[[284, 220], [1210, 1184], [2924, 2620], [5564, 5020], [6368, 6232]]
31626

标签:21,sum,numbers,time,print,Problem,divisors,amicable
来源: https://www.cnblogs.com/noonjuan/p/11031349.html