-
Notifications
You must be signed in to change notification settings - Fork 0
/
euler_012.py
40 lines (30 loc) · 1.02 KB
/
euler_012.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
"""
What is the value of the first triangle number to have over five hundred divisors?
"""
from utils import pfactors, n_divisors
from collections import defaultdict
def get_factors_quick(num, cache):
if cache.has_key(num):
return cache[num]
else:
factors = pfactors(num)
cache[num] = factors
return factors
def first_triangle_ndivisors_gt(min_divisors):
tri = lambda x: x*(x+1)/2
ndivisors = 1
curr = 1
factors_cache = {}
while ndivisors <= min_divisors:
curr += 1
if curr % 2 == 0:
prime_factors = (get_factors_quick(curr/2, factors_cache) +
get_factors_quick(curr+1, factors_cache))
else:
prime_factors = (get_factors_quick((curr+1)/2, factors_cache) +
get_factors_quick(curr, factors_cache))
factors_cache[tri(curr)] = prime_factors
ndivisors = n_divisors(prime_factors)
return tri(curr)
def p12():
return first_triangle_ndivisors_gt(500)