Non-Abundant Sums
A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of
would be , which means that is a perfect number.
A number is called deficient if the sum of its proper divisors is less than and it is called abundant if this sum exceeds .
As is the smallest abundant number, , the smallest number that can be written as the sum of two abundant numbers is . By mathematical analysis, it can be shown that all integers greater than can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.
Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.
과잉수 두 개의 합으로 나타낼 수 없는 모든 양의 정수의 합을 구하는 문제이다.
내가 생각한 구현 방식은 다음과 같다.
먼저 n의 진약수의 합을 계산해주는 함수다.
//Python
def proper_div_sum(n):
divisors = set()
for i in range(1, int(n**0.5) + 1):
if n % i == 0:
divisors.add(i)
if i != n // i: # 제곱근 중복 제거
divisors.add(n // i)
divisors.discard(n)
return sum(divisors)
Day 20에서 사용한 함수를 재활용했다.
다음은 n 이하의 모든 과잉수를 찾는 함수다.
def find_abundant_numbers(n):
numbers = []
for i in range (1, n + 1):
if proper_div_sum(i) > i:
numbers.append(i)
return numbers
==>
def find_abundant_numbers(n):
return [i for i in range(1, n + 1) if get_divisors_sum(i) > i]
이제 답을 구할 차례이다.
def solution(n):
abundant_numbers = find_abundant_numbers(n)
abundants_sum = set()
all_numbers = set(range(1, n + 1))
# 과잉수 두 개의 합으로 나타낼 수 있는 수를 계산
for i in range(len(abundant_numbers)):
for j in range(i, len(abundant_numbers)):
abundant_sum = abundant_numbers[i] + abundant_numbers[j]
if abundant_sum <= n:
abundants_sum.add(abundant_sum)
# 과잉수 두 개의 합으로 나타낼 수 없는 수의 합 계산
non_abundants_sum = all_numbers - abundants_sum
return sum(non_abundants_sum)
print(solution(28123))
>>> 4189871 # correct
오늘은 여기까지
-2025.01.12-