···11+import os # NOQA
22+import sys # NOQA
33+import re # NOQA
44+import math # NOQA
55+import fileinput
66+from itertools import product, permutations, combinations, combinations_with_replacement # NOQA
77+88+from utils import mul, factors, memoize, primes, Point # NOQA
99+1010+# Itertools Functions:
1111+# product('ABCD', repeat=2) AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD
1212+# permutations('ABCD', 2) AB AC AD BA BC BD CA CB CD DA DB DC
1313+# combinations('ABCD', 2) AB AC AD BC BD CD
1414+# combinations_with_replacement('ABCD', 2) AA AB AC AD BB BC BD CC CD DD
1515+1616+for i, line in enumerate(fileinput.input()):
1717+ pass
+29-12
2016/utils.py
···2222 for x in tup)
232324242525-def primes(n):
2626- """Returns the sorted list of primes in the range [2, n]"""
2727- limit = n + 1
2828- not_prime = set()
2929- primes = []
2525+def memoize(f):
2626+ """Simple dictionary-based memoization decorator"""
2727+ cache = {}
2828+2929+ def _mem_fn(*args):
3030+ if args not in cache:
3131+ cache[args] = f(*args)
3232+ return cache[args]
3333+3434+ _mem_fn.cache = cache
3535+ return _mem_fn
3636+3737+3838+def _eratosthenes(n):
3939+ """http://stackoverflow.com/a/3941967/239076"""
4040+ # Initialize list of primes
4141+ _primes = [True] * n
4242+4343+ # Set 0 and 1 to non-prime
4444+ _primes[0] = _primes[1] = False
30453131- for i in range(2, limit):
3232- if i in not_prime:
3333- continue
4646+ for i, is_prime in enumerate(_primes):
4747+ if is_prime:
4848+ yield i
34493535- for f in range(i*2, limit, i):
3636- not_prime.add(f)
5050+ # Mark factors as non-prime
5151+ for n in xrange(i * i, n, i):
5252+ _primes[n] = False
37533838- primes.append(i)
39544040- return primes
5555+def primes(n):
5656+ """Return a list of primes from [2, n)"""
5757+ return list(_eratosthenes(n))
415842594360@total_ordering