-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path12.py
55 lines (45 loc) · 1.27 KB
/
12.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
'''The sequence of triangle numbers is generated by adding the natural numbers.
So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28.
The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have
over five hundred divisors?'''
import time
from functools import reduce
def get_divisors(n):
fact = {}
div = 3
if n%2 == 0:
while n%2 == 0:
fact[2] = fact.get(2,0)+1
n /= 2
while div*div <= n + 1:
if n%div == 0:
while n%div == 0:
fact[div] = fact.get(div,0)+1
n /= div
div += 2
if n > 1:
fact[n] = fact.get(n,0)+1
return fact
def get_updated_divisors(a,b):
d = dict(a)
for k in b:
d[k] = d.get(k,0)+b[k]
d[2] -= 1
return reduce(lambda x,y: x*y, (v+1 for v in d.values()))
s = time.time()
def get_triangle(divisor_limit):
i = 2
triangle = 3
while True:
L = get_divisors(i)
R = get_divisors(i+1)
if get_updated_divisors(L,R) > divisor_limit:
break
i += 1
triangle += i
return triangle
get_triangle(500)
print(time.time()-s)