By replacing the 1st digit of the 2-digit number *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.
In [9]:
def prime_factors(n): # from eratosthenes
factors = []
d = 2
while n > 1:
while n % d == 0:
factors.append(d)
n /= d
d = d + 1
if d * d > n:
if n > 1:
factors.append(n)
break
return factors
def primes_less_than_n(n):
""" Returns a list of primes < n """
sieve = [True] * n
for i in xrange(3,int(n**0.5)+1,2):
if sieve[i]:
sieve[i*i::2*i]=[False]*((n-i*i-1)/(2*i)+1)
return [2] + [i for i in xrange(3,n,2) if sieve[i]]
max_num_digits = 7
all_primes = primes_less_than_n((10**max_num_digits+1)-1)
max_p = all_primes[-1]
all_primes = set(all_primes)
print len(all_primes)
def is_prime(n):
if n <= max_p:
return n in all_primes
return len(prime_factors(n)) == 1
In [39]:
import itertools
def replacement_filters(num_digits, num_to_replace):
return itertools.combinations(range(num_digits), num_to_replace)
def apply_filter(num, filt, digit):
num = list(str(num))
for d in filt:
num[d] = str(digit)
return int("".join(num))
max_num_digits = 3
def find_families(max_num_digits):
families = set()
for num_digits in range(1, max_num_digits+1):
#print "num digits", num_digits
for n in range(10**(num_digits-1), 10**(num_digits)-1):
for num_to_replace in range(1, num_digits):
for filt in replacement_filters(num_digits, num_to_replace):
family = set()
for digit in range(0,9+1):
p = apply_filter(n, filt, digit)
if p > 10**(num_digits-1) and is_prime(p):
family.add(p)
f = tuple(sorted(list(family)))
if len(f) > 1 and f not in families:
families.add(f)
if len(f) > 6:
print "Size:", len(f), ":", f
if len(f) == 8:
print n
return
find_families(max_num_digits=7)
In [ ]: