Skip to content

Commit 4045f05

Browse files
authored
Merge pull request TheAlgorithms#278 from daniel-s-ingram/master
Solution to Problem 21
2 parents a2e615e + 68e5bb4 commit 4045f05

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed

Project Euler/Problem 21/sol1.py

Lines changed: 42 additions & 0 deletions
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)

Project Euler/Problem 76/sol1.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
from __future__ import print_function
2+
'''
3+
Counting Summations
4+
Problem 76
5+
6+
It is possible to write five as a sum in exactly six different ways:
7+
8+
4 + 1
9+
3 + 2
10+
3 + 1 + 1
11+
2 + 2 + 1
12+
2 + 1 + 1 + 1
13+
1 + 1 + 1 + 1 + 1
14+
15+
How many different ways can one hundred be written as a sum of at least two positive integers?
16+
'''
17+
try:
18+
xrange #Python 2
19+
except NameError:
20+
xrange = range #Python 3
21+
22+
def partition(m):
23+
memo = [[0 for _ in xrange(m)] for _ in xrange(m+1)]
24+
for i in xrange(m+1):
25+
memo[i][0] = 1
26+
27+
for n in xrange(m+1):
28+
for k in xrange(1, m):
29+
memo[n][k] += memo[n][k-1]
30+
if n > k:
31+
memo[n][k] += memo[n-k-1][k]
32+
33+
return (memo[m][m-1] - 1)
34+
35+
print(partition(100))

0 commit comments

Comments
 (0)