def diags(matrix): for i in range(20): for j in range(20): if j < 17: yield product(matrix[i][j + k] for k in range(4)) if i < 17: yield product(matrix[i + k][j + k] for k in range(4)) if i < 17: yield product(matrix[i + k][j] for k in range(4)) if j > 2: yield product(matrix[i + k][j - k] for k in range(4))
def solution(): # Note: same method as problem 108 threshold = 4*10**6 # Get the maximum number of primes that would be required to find the least # value of `n` (using the same reasoning as that of the distinct() # function) factors = list(islice(primes(), 0, log(threshold, 2) + 1)) # Order the prime factors, and add terms with multiplicities greater than # 1 that are smaller than the largest retrieved prime factors = sorted([(p**i, p, i) for p in factors for i in takewhile(lambda n: p**n <= max(factors), count(1))]) # Prime factorization mapping for potential results, producing strictly # increasing values (before minimization) least = {} results = [] for idx, (_, p, i) in enumerate(factors): # Increase the multiplicity of p least[p] = i if distinct(least) > threshold: # Make a new copy of the factorization dictionary before the # minimization process result = dict(least.items()) # Keep track of prime factors whose multiplicity has been finalized checked = set() for _, prime, _ in reversed(factors[:idx]): if prime in checked: continue # Attempt reducing the multiplicity of `prime`... result[prime] -= 1 # ... and backtrack if necessary if distinct(result) <= threshold: result[prime] += 1 # Finalize `prime`'s multiplicity checked.add(prime) results.append(product(b**e for b, e in result.items())) return min(results)
def distinct(factors): """ Returns the number of distinct solutions to the equation: 1/x + 1/y = 1/n where n is the integer whose prime factorization corresponds to the `factors` dict (a mapping between primes and their multiplicities) """ # Uses the fact that the equation 1/x + 1/y = 1/n is equivalent to: # # (x - n)*(y - n) = n^2 # # and that the prime factorization of n^2 is the same as that of n, # except that each prime's multiplicity is doubled. return (product(2*exp + 1 for exp in factors.values()) + 1) / 2
def solution(): start = 1 limit = 10**5 + 1 # The target index in a 0-indexed sequence target = 10**4 - 1 primes = set(primes_up_to(limit)) # Reduce the set of primes to those that divide composite numbers up to # `limit` maxfac = int(limit**0.5) + 1 firstp = list(takewhile(lambda p: p < maxfac, sorted(primes))) # List of (rad(n), n) pairs radicals = [] # Mapping between numbers and their prime factors radindex = defaultdict(set) for n in range(start, limit): if n in primes: radindex[n] = {n} else: ncopy = n for p in firstp: if ncopy % p == 0: while ncopy % p == 0: ncopy /= p radindex[n].add(p) # Since ncopy < n, its prime factors have already been # computed radindex[n] |= radindex[ncopy] break radicals.append((product(radindex[n]), n)) return sorted(radicals)[target][1]
def euler008(num_digits): # TODO(durandal): rolling window, split by '0' return max( common.product([int(d) for d in DIGITS[i:i + num_digits]]) for i in range(len(DIGITS) - num_digits))
def factors(n): # assert isinstance(n, tuple) return common.product(c+1 for c in n)
def special_factors(n, cap): v = value(n) factors = common.factor(v) return len([None for i,p in enumerate(factors) if common.product(factors[:i]) < cap and common.product(factors[i:]) < cap])
def value(n): # assert isinstance(n, tuple) return common.product(p**c for p,c in zip(common.primes(), n))
def euler040(indices): return common.product( d for i, d in enumerate(itertools.islice(sequence(), max(indices))) if i + 1 in indices)
while self.cur_pos_y < self.matrix_height - 1: self.increment_position(slope_x, slope_y) if self.check_position_value() == '#': self.collisions.append((self.cur_pos_x, self.cur_pos_y)) def count_collisions(self) -> int: return len(self.collisions) if __name__ == "__main__": input_file = 'day03.txt' matrix = read_matrix(input_file, str) # Part 1 t = Toboggan(matrix) t.run(3, 1) print(f'Answer 1: {t.count_collisions()}') # Part 2 slopes = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)] num_collisions = [] for slope in slopes: t = Toboggan(matrix) t.run(slope[0], slope[1]) num_collisions.append(t.count_collisions()) total_collisions = product(num_collisions) print(f'Answer 2: {total_collisions}')
def euler040(indices): return common.product( d for i,d in enumerate(itertools.islice(sequence(), max(indices))) if i+1 in indices)
def find_values(arr: IntList, expected_value: int, group_size: int = 2): for group in combinations(arr, group_size): if sum(group) == expected_value: return product(group)
def euler008(num_digits): # TODO(durandal): rolling window, split by '0' return max(common.product([int(d) for d in DIGITS[i:i+num_digits]]) for i in range(len(DIGITS) - num_digits))
# Find the greatest product of five consecutive digits in the 1000-digit number. from common import product s = """73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450 """.replace("\n", "") v = [int(d) for d in s] print(max(product(v[i:i + 5]) for i in range(995)))
# Problem 5 # 30 November 2001 # 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. # What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? from common import factorize, merge_with_max, product from functools import reduce t = reduce(merge_with_max, (factorize(x) for x in range(2, 21))) print(product(k ** v for k, v in t.items()))