# Euler Problem 51

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.

Doesn’t this look fun. I found a great recursive permutations routine. Used it to to substitute 3 characters in all 6 digit prime numbers. Its slow but it works. Takes an average of 4-5 minutes.

import java.util.*;

public class Euler51
{
ArrayList<String> Perms = new ArrayList<String>();
public static void main(String[] args)
{
Euler51 e = new Euler51();
System.out.format(“Problem: %s\n”, e.getClass().getName());
}
public String Problem ()
{
ArrayList<Integer> P = new ArrayList<Integer>();
ArrayList<String> M = new ArrayList<String>();
ArrayList<String> A = new ArrayList<String>();
int [] digits = {0,1,2,3,4,5,6,7,8,9};
P = makePrimes(100000, 999999);
M = makePerms(“111000”);
int max = 0;
start:
for (int p: P)
{
for (String m: M)
{
A.clear();
for (int d: digits)
{
String q = “”;
for (int i = 0; i <= 5; i++)
{
if (m.charAt(i) == ‘1’)
q += d;
else
q += Integer.toString(p).charAt(i);
}
if (P.contains(Integer.parseInt(q)))
{
}
}
if (A.size() > max)
{
max = A.size();
System.out.format(“%d: %s\n”, max, A);
if (max == 8)
break start;
}
}
}
return String.valueOf(A.get(0));
}
public ArrayList<Integer> makePrimes (int min, int max)
{
ArrayList<Integer> P = new ArrayList<Integer>();
boolean [] isPrime = new boolean [max+1];
for (int i = 2; i < max; i++)
isPrime[i] = true;
for (int p = 2; p*p < max; p++)
if (isPrime[p] == true)
for (int m = p*p; m < max; m = m+p)
if (m % p == 0)
isPrime[m] = false;
for (int i = 2; i < max; i++)
if (isPrime[i] && i >= min)
return P;
}
public ArrayList<String> makePerms (String s)
{
Perms.clear();
p1(“”,s);
return Perms;
}
public void p1(String prefix, String s)
{
int N = s.length();
if (N == 0)
{
if (Perms.contains(prefix) == false)
{