Skip to content

Commit 570c27c

Browse files
Solution to Problem 21
1 parent 888c51b commit 570c27c

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Project Euler/Problem 21/sol1.py

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#-.- coding: latin-1 -.-
2+
from __future__ import print_function
3+
from math import sqrt
4+
'''
5+
Amicable Numbers
6+
Problem 21
7+
8+
Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
9+
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.
10+
11+
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.
12+
13+
Evaluate the sum of all the amicable numbers under 10000.
14+
'''
15+
try:
16+
xrange #Python 2
17+
except NameError:
18+
xrange = range #Python 3
19+
20+
def sum_of_divisors(n):
21+
total = 0
22+
for i in xrange(1, int(sqrt(n)+1)):
23+
if n%i == 0 and i != sqrt(n):
24+
total += i + n//i
25+
elif i == sqrt(n):
26+
total += i
27+
28+
return total-n
29+
30+
sums = []
31+
total = 0
32+
33+
for i in xrange(1, 10000):
34+
n = sum_of_divisors(i)
35+
36+
if n < len(sums):
37+
if sums[n-1] == i:
38+
total += n + i
39+
40+
sums.append(n)
41+
42+
print(total)

0 commit comments

Comments
 (0)