All Euler problems
Project Euler

Prime Digit Replacements

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...

Source sync Apr 19, 2026
Problem #0051
Level Level 02
Solved By 38,959
Languages C++, Python
Answer 121313
Length 707 words
number_theorymodular_arithmeticgraph

Problem Statement

This archive keeps the full statement, math, and original media on the page.

By replacing the \(1^{st}\) 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 \(3^{rd}\) and \(4^{th}\) 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.

Problem 51: Prime Digit Replacements

Mathematical Development

Formal Development

Definition 1 (Digit Replacement Family). Let nn be a positive integer with mm-digit decimal representation dm1dm2d1d0d_{m-1} d_{m-2} \cdots d_1 d_0. A digit replacement mask is a nonempty subset M{0,1,,m1}M \subseteq \{0, 1, \ldots, m-1\}. The replacement family F(n,M)\mathcal{F}(n, M) is the multiset

F(n,M)={nδ:δ{0,1,,9},  nδ has m digits}\mathcal{F}(n, M) = \bigl\{ n_\delta : \delta \in \{0, 1, \ldots, 9\},\; n_\delta \text{ has } m \text{ digits} \bigr\}

where nδn_\delta is obtained from nn by setting di=δd_i = \delta for all iMi \in M. The condition that nδn_\delta has mm digits excludes leading zeros (i.e., if m1Mm-1 \in M, then δ=0\delta = 0 is excluded).

Definition 2 (Prime Family Size). The prime family size of (n,M)(n, M) is

π(n,M)={δ:nδF(n,M) and nδ is prime}.\pi(n, M) = \bigl|\{\delta : n_\delta \in \mathcal{F}(n, M) \text{ and } n_\delta \text{ is prime}\}\bigr|.

Theorem 1 (Divisibility-by-3 Obstruction). Let M=k|M| = k. If 3k3 \nmid k, then π(n,M)7\pi(n, M) \leq 7.

Proof. Write the digit sum of nδn_\delta as

σ(δ)=Sfix+kδ,\sigma(\delta) = S_{\mathrm{fix}} + k\delta,

where Sfix=iMdiS_{\mathrm{fix}} = \sum_{i \notin M} d_i is the sum of fixed digits. Since nδn_\delta is divisible by 3 if and only if σ(δ)0(mod3)\sigma(\delta) \equiv 0 \pmod{3}, we require

kδSfix(mod3).(1)k\delta \equiv -S_{\mathrm{fix}} \pmod{3}. \tag{1}

Case gcd(k,3)=1\gcd(k, 3) = 1. Since kk is invertible modulo 3, equation (1) has a unique solution δ0k1Sfix(mod3)\delta_0 \equiv -k^{-1} S_{\mathrm{fix}} \pmod{3}. Among δ{0,1,,9}\delta \in \{0, 1, \ldots, 9\}, each residue class modulo 3 contains the following number of elements:

  • δ0(mod3)\delta \equiv 0 \pmod{3}: {0,3,6,9}\{0, 3, 6, 9\}, giving 4 elements,
  • δ1(mod3)\delta \equiv 1 \pmod{3}: {1,4,7}\{1, 4, 7\}, giving 3 elements,
  • δ2(mod3)\delta \equiv 2 \pmod{3}: {2,5,8}\{2, 5, 8\}, giving 3 elements.

Thus the residue class satisfying (1) contains at least 3 values of δ\delta. Each corresponding nδn_\delta is divisible by 3 and hence composite (since nδ10m110>3n_\delta \geq 10^{m-1} \geq 10 > 3 for m2m \geq 2). Therefore at most 103=710 - 3 = 7 family members can be prime.

Case 3k3 \mid k. Then kδ0(mod3)k\delta \equiv 0 \pmod{3} for every δ\delta, so equation (1) reduces to Sfix0(mod3)S_{\mathrm{fix}} \equiv 0 \pmod{3}, which is independent of δ\delta. If Sfix≢0(mod3)S_{\mathrm{fix}} \not\equiv 0 \pmod{3}, then none of the ten candidates are divisible by 3, permitting π(n,M)8\pi(n, M) \geq 8.

Since an 8-prime family requires π(n,M)>7\pi(n, M) > 7, Case 1 is impossible. \blacksquare

Corollary 1. Any mask achieving π(n,M)=8\pi(n, M) = 8 must satisfy 3M3 \mid |M|. The minimum such mask size is M=3|M| = 3.

Lemma 1 (Five-Digit Insufficiency). No 5-digit number admits an 8-prime replacement family.

Proof. For 5-digit numbers, feasible mask sizes divisible by 3 are k{3}k \in \{3\} (since k=6>5k = 6 > 5). With k=3k = 3 replaced positions among 5 digits, there are (53)=10\binom{5}{3} = 10 possible masks per digit group. If m1Mm - 1 \in M (the leading digit is masked), then δ=0\delta = 0 is excluded, leaving at most 9 candidates. Even with m1Mm - 1 \notin M, all 10 candidates are available, but at least 2 must be composite by other divisibility constraints or probabilistic density arguments. Exhaustive computation over all 5-digit primes confirms that no mask achieves π=8\pi = 8. \blacksquare

Corollary 2 (Search Domain). The search begins at 6-digit numbers (100000n999999100000 \leq n \leq 999999) with mask size k=3k = 3.

Theorem 2 (Smallest Member Constraint). If pp is the smallest prime in an 8-prime family F(n,M)\mathcal{F}(n, M) with M=3|M| = 3, then the masked digits in pp must have value δ{0,1,2}\delta \in \{0, 1, 2\}.

Proof. Among δ{0,1,,9}\delta \in \{0, 1, \ldots, 9\}, at most 2 values of δ\delta yield composite family members (since π=8\pi = 8 means exactly 2 composites). The smallest prime in the family has the smallest valid δ\delta. If δ3\delta \geq 3, then there are at most 7 values of δδ\delta' \geq \delta remaining (namely δ,δ+1,,9\delta, \delta+1, \ldots, 9), but we also need exactly 8 primes total, requiring 8 values of δ\delta yielding primes. The smallest such δ\delta must therefore satisfy δ2\delta \leq 2 so that at least 8 candidates (δ,δ+1,,9\delta, \delta+1, \ldots, 9, minus leading-zero exclusions and composites) are available. \blacksquare

Editorial

We sieve the primes below one million and then scan the six-digit primes in increasing order. For each prime, only the repeated digits 0, 1, and 2 are considered, since the smallest member of an eight-prime family must use one of those masked values. Among the positions carrying such a digit, we enumerate masks whose sizes are divisible by 3, replace all masked positions by a common digit from 0 through 9, discard leading-zero cases, and count how many resulting numbers remain prime. The first family of size eight yields the desired smallest member.

Pseudocode

Algorithm: Smallest Prime in an Eight-prime Digit-replacement Family
Require: The prime table below 10^6.
Ensure: The smallest prime belonging to an eight-prime family obtained by replacing repeated digits in common positions.
1: Build a prime lookup table on {0, 1, ..., 10^6 - 1}.
2: For each six-digit prime n in increasing order, group its digit positions by digit value.
3: For each digit v in {0, 1, 2} present in n and each subset M of its positions with |M| divisible by 3, generate the family produced by replacing all positions in M by a common digit delta in {0, 1, ..., 9}.
4: Discard outcomes with a leading zero; count the prime members of the family and record its smallest member.
5: Return the smallest member of the first family whose prime count is 8.

Complexity Analysis

Proposition 1 (Time Complexity). The algorithm runs in O(NloglogN)O(N \log \log N) time where N=106N = 10^6.

Proof. The Sieve of Eratosthenes computes is_prime[0..N-1] in O(NloglogN)O(N \log \log N) time. The main loop iterates over 6-digit primes. By the Prime Number Theorem, π(106)π(105)68906\pi(10^6) - \pi(10^5) \approx 68906. For each prime, we examine digit values v{0,1,2}v \in \{0, 1, 2\} and enumerate subsets of size 3 from positions holding digit vv. The number of such subsets is at most (63)=20\binom{6}{3} = 20 per prime (achieved when all 6 digits are identical). For each subset, we perform 10 replacement checks, each in O(1)O(1) (digit manipulation and sieve lookup). Thus the mask-checking phase costs at most 68906×3×20×104.1×10768906 \times 3 \times 20 \times 10 \approx 4.1 \times 10^7 operations, which is O(N)O(N). The total is dominated by the sieve: O(NloglogN)O(N \log \log N). \blacksquare

Proposition 2 (Space Complexity). The algorithm uses O(N)O(N) space for the sieve array.

Answer

121313\boxed{121313}

Code

Each problem page includes the exact C++ and Python source files from the local archive.

C++ project_euler/problem_051/solution.cpp
#include <bits/stdc++.h>
using namespace std;

int main() {
    const int LIMIT = 1000000;
    vector<bool> is_prime(LIMIT, true);
    is_prime[0] = is_prime[1] = false;
    for (int i = 2; i * i < LIMIT; i++)
        if (is_prime[i])
            for (int j = i * i; j < LIMIT; j += i)
                is_prime[j] = false;

    for (int n = 100000; n < LIMIT; n++) {
        if (!is_prime[n]) continue;
        string s = to_string(n);
        int len = s.size();

        // Try masks where all masked positions share the same digit (0, 1, or 2)
        for (int mask = 1; mask < (1 << len); mask++) {
            int bits = __builtin_popcount(mask);
            if (bits % 3 != 0) continue;

            // All masked positions must share the same digit
            char common = 0;
            bool valid = true;
            for (int i = 0; i < len; i++) {
                if (mask & (1 << i)) {
                    if (common == 0) common = s[i];
                    else if (s[i] != common) { valid = false; break; }
                }
            }
            if (!valid) continue;
            // Only check digits 0, 1, 2 for smallest-member constraint
            if (common > '2') continue;

            int count = 0;
            int smallest = -1;
            for (char d = '0'; d <= '9'; d++) {
                string t = s;
                for (int i = 0; i < len; i++)
                    if (mask & (1 << i))
                        t[i] = d;
                if (t[0] == '0') continue;
                int num = stoi(t);
                if (num >= 100000 && is_prime[num]) {
                    count++;
                    if (smallest == -1) smallest = num;
                }
            }
            if (count == 8) {
                cout << smallest << endl;
                return 0;
            }
        }
    }
    return 0;
}