본문 바로가기

파이썬

[Project Euler]21. Amicable numbers

[문제]
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.

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.

 

[풀이]
import math

def findDivisors(n):
    result=0
    if int(math.sqrt(n))==1:
        return 1
    
    for i in range(1, int(math.sqrt(n))):
        if n % i ==0:
            if i * i==n:
                result+=i
            else:
                result+=i
                result+=int(n/i)

    result-=n     
    return(result)


def isAmicable(n):
    intFindDivisor=findDivisors(n)
    intAmicable=findDivisors(intFindDivisor)
    if intFindDivisor==intAmicable:
        return False

    return (intAmicable==n)

result=0

for i in range(1,10000):
    if isAmicable(i):
        if findDivisors(i)<10000:
            result=result+i

print(result)

'''
약수를 구하는 함수랑 우호적인 쌍이 있는지 확인하는 함수를 만들었다.
isAmicable()은 우호적인 쌍이 자기 자신이라면 False를 반환하도록 했다.

처음엔 자기 자신까지 우호적인 쌍에 포함해서 구하느라 답이 안나왔었는데
생각해보니.. 자기 자신이 그렇다면 우호적인 쌍이 아닐 것 같아서
제외하고 구하니 바로 답이 나왔다.
'''