All Euler problems
Project Euler

Friend Numbers

Let s(n) denote the sorted tuple of decimal digits of n. Two positive integers a and b are friend numbers if s(a) = s(b). Define f(n) as the number of positive integers m <= 10^n such that m has no...

Source sync Apr 19, 2026
Problem #0612
Level Level 17
Solved By 819
Languages C++, Python
Answer 819963842
Length 531 words
combinatoricsmodular_arithmeticnumber_theory

Problem Statement

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

Let’s call two numbers friend numbers if their representation in base \(10\) has at least one common digit.

E.g. \(1123\) and \(3981\) are friend numbers.

Let \(f(n)\) be the number of pairs \((p,q)\) with \(1\le p < q < n\) such that \(p\) and \(q\) are friend numbers.

\(f(100)=1539\).

Find \(f(10^{18}) \bmod 1000267129\).

Problem 612: Friend Numbers

Mathematical Foundation

Definition. A digit signature of a non-negative integer mm is the multiset of its decimal digits. Two integers are friends if they share the same digit signature. We say mm is friendless-to-primes if no permutation of its digits (with no leading zero) forms a prime.

Theorem 1 (Reduction to Digit Multisets). The count f(n)f(n) equals the number of integers m[1,10n]m \in [1, 10^n] such that for every permutation σ\sigma of the digits of mm (ignoring those with leading zeros), σ(m)\sigma(m) is composite or 1\le 1.

Proof. This is a direct restatement of the definition. \square

Lemma 1 (Divisibility Filter). Let D=(d0,d1,,d9)D = (d_0, d_1, \ldots, d_9) be a digit frequency vector where did_i is the count of digit ii, and D=di|D| = \sum d_i is the total number of digits. A necessary condition for all permutations to be composite is:

  1. Divisibility by 3: If 3(d1+2d2+3d3++9d9)3 \mid (d_1 + 2d_2 + 3d_3 + \cdots + 9d_9), i.e., 3digitsum(m)3 \mid \text{digitsum}(m), then every permutation is divisible by 3. If additionally D>1|D| > 1 and the digit set allows numbers >3> 3, all permutations are composite (except possibly 3 itself).
  2. All-even final digit: If every permutation ends in an even digit or 5, then every permutation is divisible by 2 or 5.

Proof. (1) The digit sum is invariant under permutation, and ndigitsum(n)(mod3)n \equiv \text{digitsum}(n) \pmod{3}. If the digit sum is divisible by 3, every permutation is divisible by 3. (2) A number is even iff its last digit is even, and divisible by 5 iff its last digit is 0 or 5. If all digits are from {0,2,4,5,6,8}\{0, 2, 4, 5, 6, 8\}, every permutation ends in one of these, hence is divisible by 2 or 5. \square

Theorem 2 (Counting via Inclusion—Exclusion on Digit Multisets). Group all integers by digit signature. For each signature DD with Dn|D| \le n digits, determine whether any permutation is prime. The count of friendless-to-primes integers with signature DD is:

c(D)={P(D)if no permutation of D is prime,0otherwise,c(D) = \begin{cases} P(D) & \text{if no permutation of } D \text{ is prime}, \\ 0 & \text{otherwise}, \end{cases}

where P(D)P(D) is the number of valid (no leading zero) arrangements of DD:

P(D)=D!i=09di!(D1)!(d01)!i=19di!1[d0>0].P(D) = \frac{|D|!}{\prod_{i=0}^{9} d_i!} - \frac{(|D|-1)!}{(d_0 - 1)! \prod_{i=1}^{9} d_i!} \cdot \mathbb{1}[d_0 > 0].

Then f(n)=D:Dnc(D)f(n) = \sum_{D:\, |D| \le n} c(D).

Proof. The multinomial coefficient counts total arrangements; subtracting those with a leading zero (fixing 0 in the first position and permuting the rest) gives valid integers. Summing over all friendless signatures yields f(n)f(n). \square

Lemma 2 (Primality Check Sufficiency). For a digit signature DD with digit sum not divisible by 3 and containing at least one odd digit not equal to 5, it suffices to check a bounded number of permutations for primality using a deterministic Miller—Rabin test.

Proof. By Lemma 1, if 3digitsum3 \nmid \text{digitsum} and the digits include {1,3,7,9}\{1, 3, 7, 9\}, then permutations ending in those digits are not automatically composite. For signatures with D22|D| \le 22, the number of permutations is at most 22!/di!22! / \prod d_i!, and probabilistic or deterministic primality tests apply to each candidate. \square

Editorial

Count numbers whose digit permutations include at least one prime. We quick filters. We then all permutations divisible by 3 => friendless (unless 3 itself is a perm). Finally, otherwise, enumerate permutations ending in odd digit != 5.

Pseudocode

Quick filters
All permutations divisible by 3 => friendless (unless 3 itself is a perm)
Otherwise, enumerate permutations ending in odd digit != 5
and check primality
for each permutation sigma of D with no leading zero

Complexity Analysis

  • Time: O ⁣((n+99)K)O\!\left(\binom{n+9}{9} \cdot K\right) where (n+99)\binom{n+9}{9} is the number of distinct digit signatures with at most nn digits, and KK is the cost of the primality check per signature (ranging from O(1)O(1) for filtered cases to O(n!/di!)O(n!/\prod d_i!) in the worst case, though filters eliminate most signatures).
  • Space: O(n)O(n) for the current signature and primality workspace.

Answer

819963842\boxed{819963842}

Code

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

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

bool is_prime(int n) {
    if (n < 2) return false;
    if (n < 4) return true;
    if (n % 2 == 0 || n % 3 == 0) return false;
    for (int i = 5; i * i <= n; i += 6)
        if (n % i == 0 || n % (i+2) == 0) return false;
    return true;
}

int main() {
    int N = 1000, count = 0;
    for (int n = 2; n <= N; n++) {
        string s = to_string(n);
        sort(s.begin(), s.end());
        bool found = false;
        do {
            if (s[0] != '0' && is_prime(stoi(s))) { found = true; break; }
        } while (next_permutation(s.begin(), s.end()));
        if (found) count++;
    }
    cout << count << endl;
    return 0;
}