All Euler problems
Project Euler

Primes with Runs

For n -digit primes, define: M(n, d): the maximum number of repeated occurrences of digit d in an n -digit prime, N(n, d): the count of n -digit primes achieving M(n, d) repetitions of d, S(n, d):...

Source sync May 21, 2026
Problem #0111
Level Level 05
Solved By 8,498
Languages C++, Python
Answer 612407567715
Length 545 words
modular_arithmeticnumber_theorygreedy

Problem Statement

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

Considering $4$-digit primes containing repeated digits it is clear that they cannot all be the same: $1111$ is divisible by $11$, $2222$ is divisible by $22$, and so on. But there are nine $4$-digit primes containing three ones: $$1117, 1151, 1171, 1181, 1511, 1811, 2111, 4111, 8111.$$ We shall say that $M(n, d)$ represents the maximum number of repeated digits for an $n$-digit prime where $d$ is the repeated digit, $N(n, d)$ represents the number of such primes, and $S(n, d)$ represents the sum of these primes.

So $M(4, 1) = 3$ is the maximum number of repeated digits for a $4$-digit prime where one is the repeated digit, there are $N(4, 1) = 9$ such primes, and the sum of these primes is $S(4, 1) = 22275$. It turns out that for $d = 0$, it is only possible to have $M(4, 0) = 2$ repeated digits, but there are $N(4, 0) = 13$ such cases.

In the same way we obtain the following results for $4$-digit primes.

Digit, $d$$M(4, d)$$N(4, d)$$S(4, d)$
021267061
13922275
2312221
331246214
4328888
5315557
6316661
73957863
8318887
93748073

For $d = 0$ to $9$, the sum of all $S(4, d)$ is $273700$.

Find the sum of all $S(10, d)$.

Problem 111: Primes with Runs

Mathematical Development

Theorem 1 (Repdigit composite bound). A repdigit number dd⋯d⏟n\underbrace{dd \cdots d}_{n} with n≥2n \geq 2 and 1≤d≤91 \leq d \leq 9 is composite.

Proof. Write dd⋯d⏟n=d⋅Rn\underbrace{dd \cdots d}_{n} = d \cdot R_n where Rn=10n−19R_n = \frac{10^n - 1}{9} is the repunit of length nn. For n≥2n \geq 2, we have Rn≥R2=11R_n \geq R_2 = 11, so the factorization d⋅Rnd \cdot R_n is nontrivial (both factors exceed 1). ■\blacksquare

Corollary 1. For all n≥2n \geq 2 and digits d∈{0,1,…,9}d \in \{0, 1, \ldots, 9\}, M(n,d)≤n−1M(n, d) \leq n - 1.

Proof. If d=0d = 0, an nn-digit number cannot have all nn digits equal to 0 (it would be zero). If d≥1d \geq 1, the nn-digit number dd⋯d⏟n\underbrace{dd \cdots d}_n is composite by Theorem 1. In both cases, no nn-digit prime consists entirely of a single repeated digit. ■\blacksquare

Theorem 2 (Candidate enumeration). For fixed nn, dd, and kk (the number of positions holding digit dd), the number of candidate nn-digit numbers with exactly kk positions equal to dd is

C(n,k,d)=(nn−k)⋅9n−k−E(n,k,d)C(n, k, d) = \binom{n}{n - k} \cdot 9^{n - k} - E(n, k, d)

where E(n,k,d)E(n, k, d) counts candidates with a leading zero.

Proof. Select which n−kn - k of the nn positions hold a digit other than dd: there are (nn−k)\binom{n}{n-k} ways. Each such position admits 9 choices from {0,1,…,9}∖{d}\{0, 1, \ldots, 9\} \setminus \{d\}, yielding (nn−k)⋅9n−k\binom{n}{n-k} \cdot 9^{n-k} candidates in total. However, any candidate with leading digit 0 does not represent a valid nn-digit number and must be excluded. ■\blacksquare

Lemma 1 (Deterministic primality for 10-digit numbers). The Miller—Rabin primality test with witness set W={2,3,5,7,11,13}W = \{2, 3, 5, 7, 11, 13\} is deterministic for all integers n<3.2×1013n < 3.2 \times 10^{13}. In particular, it correctly classifies every 10-digit number.

Proof. Jaeschke (1993) proved that no strong pseudoprime to all bases in WW exists below 3.2×10133.2 \times 10^{13}. Since every 10-digit number satisfies n<1010<3.2×1013n < 10^{10} < 3.2 \times 10^{13}, the test is infallible in this range. ■\blacksquare

Theorem 3 (Greedy descent correctness). The algorithm that sets k=n−1k = n - 1 and decreases kk by 1, at each level exhaustively enumerating all nn-digit candidates with exactly kk copies of digit dd and testing each for primality, correctly determines M(n,d)M(n, d): the first level kk at which a prime is found equals M(n,d)M(n, d).

Proof. By definition, M(n,d)=max⁡{k:∃ an n-digit prime with exactly k copies of d}M(n, d) = \max\{k : \exists \text{ an } n\text{-digit prime with exactly } k \text{ copies of } d\}. Corollary 1 gives M(n,d)≤n−1M(n, d) \leq n - 1. The algorithm starts at this upper bound and descends. At each level kk, it performs an exhaustive search over all valid candidates (Theorem 2) and applies a correct primality test (Lemma 1). Hence, the first kk yielding at least one prime is the maximum such kk, which is M(n,d)M(n, d) by definition. ■\blacksquare

Editorial

The quantity M(10,d)M(10,d) is defined by a maximum repetition count, so the search should start from the top. For a fixed digit dd, we first ask whether a 10-digit prime exists with nine copies of dd. If not, we allow two non-dd positions, then three, and so on. The first repetition count that produces any prime is automatically the maximal one, so all primes found at that level contribute to S(10,d)S(10,d).

The implementation follows that definition directly. It chooses which positions are allowed to differ from dd, fills those positions with digits other than dd, rejects candidates with a leading zero, and runs a deterministic Miller—Rabin test on the resulting 10-digit number. Summing the primes found at the first successful level for each digit d=0,1,…,9d = 0,1,\ldots,9 gives the required total.

Pseudocode

Set the overall sum to zero.

For each repeated digit d from 0 through 9:
    Try repetition counts from 9 downward until a prime appears.
    For the current repetition count, choose the positions that are allowed to differ from d.
    Fill those free positions with digits other than d to form every candidate number with exactly that many copies of d.
    Discard any candidate with a leading zero, and test every remaining candidate for primality.
    If at least one prime is found at this level, add their sum to the overall total and stop descending for this digit.

Return the overall sum.

Complexity Analysis

  • Time. For each digit d∈{0,…,9}d \in \{0, \ldots, 9\}, the greedy descent starts at k=9k = 9 (i.e., n−k=1n - k = 1 free position). At level k=9k = 9, the candidate count is (101)⋅9=90\binom{10}{1} \cdot 9 = 90. At level k=8k = 8, it is (102)⋅92=3645\binom{10}{2} \cdot 9^2 = 3645. In practice, most digits find primes at k=9k = 9 or k=8k = 8. Over all 10 digits, the total number of candidates tested is at most 10×3645=36,45010 \times 3645 = 36{,}450. Each Miller—Rabin test costs O(log⁡2n)O(\log^2 n) with 6 witnesses, where n<1010n < 10^{10}. Since log⁡2(1010)≈33\log_2(10^{10}) \approx 33, each test performs a bounded number of modular exponentiations. Total: O(1)O(1) (constant with respect to the problem parameters).
  • Space. O(1)O(1) beyond a small list of primes per (d,k)(d, k) pair.

Answer

612407567715\boxed{612407567715}

Code

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

C++ project_euler/problem_111/solution.cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef __int128 lll;

bool miller_rabin(ll n, ll a) {
    if (n % a == 0) return n == a;
    ll d = n - 1;
    int r = 0;
    while (d % 2 == 0) { d /= 2; r++; }
    ll x = 1, base = a % n, dd = d;
    while (dd > 0) {
        if (dd & 1) x = (lll)x * base % n;
        base = (lll)base * base % n;
        dd >>= 1;
    }
    if (x == 1 || x == n - 1) return true;
    for (int i = 0; i < r - 1; i++) {
        x = (lll)x * x % n;
        if (x == n - 1) return true;
    }
    return false;
}

bool is_prime(ll n) {
    if (n < 2) return false;
    for (ll a : {2, 3, 5, 7, 11, 13})
        if (!miller_rabin(n, a)) return false;
    return true;
}

int main() {
    const int n = 10;
    ll total = 0;
    for (int d = 0; d <= 9; d++) {
        for (int k = n - 1; k >= 1; k--) {
            int free = n - k;
            vector<int> combo(free);
            ll sum_p = 0;
            function<void(int, int)> gen_combos = [&](int start, int idx) {
                if (idx == free) {
                    function<void(int, ll)> gen_digits = [&](int i, ll num) {
                        if (i == n) {
                            if (num >= 1000000000LL && is_prime(num))
                                sum_p += num;
                            return;
                        }
                        bool is_free = false;
                        for (int j = 0; j < free; j++)
                            if (combo[j] == i) { is_free = true; break; }
                        if (!is_free) {
                            gen_digits(i + 1, num * 10 + d);
                        } else {
                            for (int dd = 0; dd <= 9; dd++) {
                                if (dd == d) continue;
                                gen_digits(i + 1, num * 10 + dd);
                            }
                        }
                    };
                    gen_digits(0, 0);
                    return;
                }
                for (int i = start; i < n; i++) {
                    combo[idx] = i;
                    gen_combos(i + 1, idx + 1);
                }
            };
            gen_combos(0, 0);
            if (sum_p > 0) { total += sum_p; break; }
        }
    }
    cout << total << endl;
    return 0;
}