Project Euler Problem 051
Statement
By replacing the 1st digit of *3, it turns out that six of the nine possible values: 13, 23, 43, 53, 73, and 83, are all prime.
By replacing the 3rd and 4th digits of 56**3 with the same digit, this 5-digit number is the first example having seven primes among the ten generated numbers, yielding the family: 56003, 56113, 56333, 56443, 56663, 56773, and 56993. Consequently 56003, being the first member of this family, is the smallest prime with this property.
Find the smallest prime which, by replacing part of the number (not necessarily adjacent digits) with the same digit, is part of an eight prime value family.
Solution
Well, basically brute-force solution.
from itertools import permutations, takewhile from CommonFunctions import find_primes_less_than def build_masks(n): masks = set() for i in range(1, n): zeros = [0 for x in range(n-i)] ones = [1 for x in range(i)] for mask in permutations(zeros + ones): masks.add(mask) return masks def apply_mask(n, mask): str_n = str(n) result = "" remain = "" for i in range(len(mask)): result += mask[i] and str_n[i] or "" remain += (not mask[i]) and str_n[i] or "" return result, int(remain) if __name__ == '__main__': primes = find_primes_less_than(1000000) length = 0 result = None for prime in takewhile(lambda x: result is None, primes): if len(str(prime)) > length: length = len(str(prime)) masks = build_masks(length) groups = {} for mask in masks: res, remain = apply_mask(prime, mask) if min(res) == max(res): if mask not in groups: groups[mask] = {} if remain not in groups[mask]: groups[mask][remain] = [] groups[mask][remain].append(prime) if len(groups[mask][remain]) == 8: result = min(groups[mask][remain]) break print("The result is:", result)
The Python file is available for download here.