Skip to content

Commit 9990bd9

Browse files
Hyftarstokhos
authored andcommitted
Add problem 23 solution (TheAlgorithms#1261)
1 parent debf664 commit 9990bd9

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

project_euler/problem_23/sol1.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
"""
2+
A perfect number is a number for which the sum of its proper divisors is exactly
3+
equal to the number. For example, the sum of the proper divisors of 28 would be
4+
1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
5+
6+
A number n is called deficient if the sum of its proper divisors is less than n
7+
and it is called abundant if this sum exceeds n.
8+
9+
As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest
10+
number that can be written as the sum of two abundant numbers is 24. By
11+
mathematical analysis, it can be shown that all integers greater than 28123
12+
can be written as the sum of two abundant numbers. However, this upper limit
13+
cannot be reduced any further by analysis even though it is known that the
14+
greatest number that cannot be expressed as the sum of two abundant numbers
15+
is less than this limit.
16+
17+
Find the sum of all the positive integers which cannot be written as the sum
18+
of two abundant numbers.
19+
"""
20+
21+
def solution(limit = 28123):
22+
"""
23+
Finds the sum of all the positive integers which cannot be written as
24+
the sum of two abundant numbers
25+
as described by the statement above.
26+
27+
>>> solution()
28+
4179871
29+
"""
30+
sumDivs = [1] * (limit + 1)
31+
32+
for i in range(2, int(limit ** 0.5) + 1):
33+
sumDivs[i * i] += i
34+
for k in range(i + 1, limit // i + 1):
35+
sumDivs[k * i] += k + i
36+
37+
abundants = set()
38+
res = 0
39+
40+
for n in range(1, limit + 1):
41+
if sumDivs[n] > n:
42+
abundants.add(n)
43+
44+
if not any((n - a in abundants) for a in abundants):
45+
res+=n
46+
47+
return res
48+
49+
50+
if __name__ == "__main__":
51+
print(solution())

0 commit comments

Comments
 (0)