Open Source · 7 Languages · 900+ Problems

Project Euler Solutions

Complete solutions in C++, Python & Java — with step-by-step mathematical explanations

All Problems

Problem 924: Larger Digit Permutation II

View on Project Euler

Project Euler Problem 924 Solution

EulerSolve provides an optimized solution for Project Euler Problem 924, Larger Digit Permutation II, with C++, Python, Java, and a step-by-step mathematical explanation.

Problem Summary Define \(\operatorname{nextPerm}(m)\) to be the smallest integer strictly larger than \(m\) that uses exactly the same decimal digits as \(m\). If no larger rearrangement exists, its value is \(0\). The sequence in this problem is $a_0=0,\qquad a_n=a_{n-1}^2+2,$ and we must evaluate $U(N)=\sum_{n=1}^{N}\operatorname{nextPerm}(a_n)\pmod{10^9+7},\qquad N=10^{16}.$ The first terms are still small enough to inspect directly: $a_1=2,\quad a_2=6,\quad a_3=38,\quad a_4=1446,\quad a_5=2090918,\quad a_6=4371938082726.$ From that point on, the exact integers become far too large for direct decimal manipulation. The implementations therefore track only two finite-state shadows of the sequence: the residue \(a_n \bmod (10^9+7)\) and the final \(11\) decimal digits of \(a_n\). Mathematical Approach The solution is built around one problem-specific decomposition. For large \(n\), the next larger digit permutation of \(a_n\) is obtained by leaving the high decimal prefix alone and changing only the last \(11\) digits. That converts a huge decimal problem into the sum of a modular orbit and a fixed-width tail correction. Exact Prefix and the Turning Point at \(n=6\) The first five terms can be handled exactly....

Detailed mathematical approach

Problem Summary

Define \(\operatorname{nextPerm}(m)\) to be the smallest integer strictly larger than \(m\) that uses exactly the same decimal digits as \(m\). If no larger rearrangement exists, its value is \(0\). The sequence in this problem is

$a_0=0,\qquad a_n=a_{n-1}^2+2,$

and we must evaluate

$U(N)=\sum_{n=1}^{N}\operatorname{nextPerm}(a_n)\pmod{10^9+7},\qquad N=10^{16}.$

The first terms are still small enough to inspect directly:

$a_1=2,\quad a_2=6,\quad a_3=38,\quad a_4=1446,\quad a_5=2090918,\quad a_6=4371938082726.$

From that point on, the exact integers become far too large for direct decimal manipulation. The implementations therefore track only two finite-state shadows of the sequence: the residue \(a_n \bmod (10^9+7)\) and the final \(11\) decimal digits of \(a_n\).

Mathematical Approach

The solution is built around one problem-specific decomposition. For large \(n\), the next larger digit permutation of \(a_n\) is obtained by leaving the high decimal prefix alone and changing only the last \(11\) digits. That converts a huge decimal problem into the sum of a modular orbit and a fixed-width tail correction.

Exact Prefix and the Turning Point at \(n=6\)

The first five terms can be handled exactly. Their next larger digit permutations are

$\operatorname{nextPerm}(2)=0,\qquad \operatorname{nextPerm}(6)=0,\qquad \operatorname{nextPerm}(38)=83,$

$\operatorname{nextPerm}(1446)=1464,\qquad \operatorname{nextPerm}(2090918)=2090981.$

So the exact prefix contributes

$U(5)=0+0+83+1464+2090981=2092528.$

The real difficulty begins at \(a_6\). After that, the numbers are already too large to compute \(\operatorname{nextPerm}(a_n)\) by operating on the full decimal expansion for anything like \(10^{16}\) terms.

Two Finite-State Projections of the Recurrence

Let

$p=10^9+7,\qquad a_n=10^{11}q_n+t_n,\qquad 0\le t_n<10^{11}.$

Here \(t_n\) is treated as an \(11\)-digit decimal word, with leading zeros when necessary. This is important because next permutation is a positional digit operation, so those leading zeros still occupy digit slots.

Define

$x_n\equiv a_n\pmod p.$

Then the recurrence immediately gives

$x_{n+1}\equiv x_n^2+2\pmod p,\qquad t_{n+1}\equiv t_n^2+2\pmod{10^{11}}.$

The padded tail at the cutoff point is

$t_5=00002090918.$

So beyond the exact prefix, all arithmetic can be advanced inside the finite rings modulo \(p\) and modulo \(10^{11}\).

The 11-Digit Tail Correction

For the orbit relevant to this problem, the implementations exploit the invariant that from \(n\ge 6\) onward, the standard next-permutation pivot, swap, and suffix reversal all occur inside the last \(11\) decimal positions. If \(\operatorname{nextPerm}_{11}(t)\) denotes the next lexicographic permutation of the \(11\)-digit word \(t\), define

$\Delta(t)=\operatorname{nextPerm}_{11}(t)-t.$

Under that invariant,

$\operatorname{nextPerm}(a_n)=10^{11}q_n+\operatorname{nextPerm}_{11}(t_n)=a_n+\Delta(t_n)\qquad (n\ge 6).$

Therefore

$\operatorname{nextPerm}(a_n)\equiv x_n+\Delta(t_n)\pmod p.$

This is the decisive simplification: the huge decimal rearrangement is replaced by a modular term \(x_n\) and a small fixed-width correction. The C++ implementation checks this identity against exact big-integer values for \(n=6,\dots,15\), and the full tail sweep confirms that every visited \(11\)-digit tail on the relevant orbit has a valid next lexicographic rearrangement.

Decomposing the Full Sum

Let

$S_{\text{small}}(N)=\sum_{n=1}^{\min\{N,5\}}\operatorname{nextPerm}(a_n).$

Then for \(N\ge 6\),

$U(N)\equiv S_{\text{small}}(N)+\sum_{n=6}^{N}x_n+\sum_{n=6}^{N}\Delta(t_n)\pmod p.$

So after the first five terms, the task splits into two separate long sums: one over the orbit modulo \(p\), and one over the tail correction along the orbit modulo \(10^{11}\).

Eventually Periodic Orbit Modulo \(10^9+7\)

The map \(x\mapsto x^2+2 \pmod p\) acts on a finite state space, so the orbit starting from \(x_0=0\) is eventually periodic. The implementations find

$\mu=39911,\qquad \lambda=21353,$

where \(\mu\) is the preperiod length and \(\lambda\) is the cycle length. If

$P(n)=\sum_{k=0}^{n}x_k,\qquad C=\sum_{j=0}^{\lambda-1}x_{\mu+j},$

then for every \(n\ge \mu\), with

$r=(n-\mu+1)\bmod\lambda,$

we get

$P(n)\equiv P(\mu-1)+\left\lfloor\frac{n-\mu+1}{\lambda}\right\rfloor C+\sum_{j=0}^{r-1}x_{\mu+j}\pmod p.$

That turns \(\sum_{n=6}^{N}x_n\) into a prefix-sum query on one precomputed orbit.

The Full Tail Orbit Modulo \(10^{11}\)

The tail sequence also lives in a finite state space. Starting from \(t_5=00002090918\), the implementations iterate

$t_{n+1}\equiv t_n^2+2\pmod{10^{11}}$

and use the fact that the relevant orbit has length

$L_{\text{tail}}=15625000=8\cdot 5^9.$

After exactly \(L_{\text{tail}}\) steps, the tail returns to \(t_5\). If

$D=\sum_{i=0}^{L_{\text{tail}}-1}\Delta(t_{6+i})\pmod p,$

and

$Q=\left\lfloor\frac{N-5}{L_{\text{tail}}}\right\rfloor,\qquad R=(N-5)\bmod L_{\text{tail}},$

then

$\sum_{n=6}^{N}\Delta(t_n)\equiv QD+\sum_{i=0}^{R-1}\Delta(t_{6+i})\pmod p.$

This is the second compression step: a sum over almost \(10^{16}\) indices collapses to one full-cycle sum and one remainder sum.

Worked Example: the First Large Term

The transition from \(a_5\) to \(a_6\) shows the mechanism clearly. We have

$a_5=2090918,\qquad \operatorname{nextPerm}(a_5)=2090981,$

and then

$a_6=a_5^2+2=4371938082726.$

Its \(11\)-digit tail is

$t_6=71938082726.$

The next lexicographic permutation of this \(11\)-digit word is

$71938082726\to 71938082762,$

so

$\Delta(t_6)=71938082762-71938082726=36.$

Therefore

$\operatorname{nextPerm}(a_6)=a_6+36=4371938082762.$

This is exactly the same local correction rule later reused for every large term. As a further checkpoint, the exact prefix plus the first five large-regime terms satisfy

$U(10)\equiv 543870437\pmod p.$

How the Code Works

Exact Prefix and Residue Orbit

The C++, Python, and Java implementations first compute the exact contributions for \(n=1,\dots,5\), because those numbers are still small enough for direct decimal next-permutation arithmetic. They then build the orbit of \(x_{n+1}=x_n^2+2\pmod p\), stop when the first repeated state appears, and store prefix sums so that any interval sum of the residue sequence can be answered in constant additional time.

Tail Sweep and Quotient-Remainder Expansion

Next, the implementation starts from the padded tail \(00002090918\), advances the recurrence modulo \(10^{11}\), computes the \(11\)-digit next-permutation delta at each step, and accumulates one full orbit sum \(D\). A quotient-remainder split then expands that one-cycle total to all indices from \(n=6\) up to \(n=10^{16}\).

Consistency Checks

The C++ implementation also performs explicit validations. It checks the exact value of \(U(10)\), compares the decomposition against exact big-integer values for the early large terms, and verifies that the tail returns to its starting point after exactly \(L_{\text{tail}}\) steps. The Python and Java implementations follow the same mathematical decomposition but omit those explicit assertions.

Complexity Analysis

The orbit modulo \(p\) stores \(\mu+\lambda=61264\) states, so that phase costs \(O(\mu+\lambda)\) time and memory. The dominant work is the single sweep over the tail orbit of length \(L_{\text{tail}}=15625000\), plus at most one shorter remainder sweep. Hence the overall complexity is

$O(\mu+\lambda+L_{\text{tail}})$

time and

$O(\mu+\lambda)$

memory.

The gain is dramatic: the method never tries to materialize \(a_n\) for \(n\) anywhere near \(10^{16}\), and it never runs decimal next-permutation logic on astronomically large integers.

Footnotes and References

  1. Project Euler problem page: https://projecteuler.net/problem=924
  2. Lexicographic next permutation: Wikipedia - Permutation generation in lexicographic order
  3. Cycle detection in finite state spaces: Wikipedia - Cycle detection
  4. Modular arithmetic: Wikipedia - Modular arithmetic
  5. Recurrence relations: Wikipedia - Recurrence relation

Mathematical approach · C++ solution · Python solution · Java solution

Previous: Problem 923 · All Project Euler solutions · Next: Problem 925

Need help with a problem? Ask me! 💡
e
✦ Euler GLM 5.2
Hi! I'm Euler. Ask me anything about Project Euler problems, math concepts, or solution approaches! 🧮