Project Euler Lab - Problem 693

#693 - Finite Sequence Generator

● ResearchOfficial difficulty: 85%Maximize/minimize an objectiveTier C - reduced scale in browser; full scale in notebookNot viewed
↖ Euler Lab

Two positive integers \(x\) and \(y\) (\(x > y\)) can generate a sequence in the following manner:

  • \(a_x = y\) is the first term,
  • \(a_{z+1} = a_z^2 \bmod z\) for \(z = x, x+1,x+2,\ldots\) and
  • the generation stops when a term becomes \(0\) or \(1\).

The number of terms in this sequence is denoted \(l(x,y)\).

For example, with \(x = 5\) and \(y = 3\), we get \(a_5 = 3\), \(a_6 = 3^2 \bmod 5 = 4\), \(a_7 = 4^2\bmod 6 = 4\), etc. Giving the sequence of 29 terms:
\( 3,4,4,2,4,7,9,4,4,3,9,6,4,16,4,16,16,4,16,3,9,6,10,19,25,16,16,8,0 \)
Hence \(l(5,3) = 29\).

\(g(x)\) is defined to be the maximum value of \(l(x,y)\) for \(y \lt x\). For example, \(g(5) = 29\).

Further, define \(f(n)\) to be the maximum value of \(g(x)\) for \(x \le n\). For example, \(f(100) = 145\) and \(f(10\,000) = 8824\).

Find \(f(3\,000\,000)\).

This problem is taken from Project Euler, Problem 693.
Problem text © Project Euler, licensed under CC BY-NC-SA 4.0. Original: projecteuler.net/problem=693. Published Saturday, 14th December 2019, 04:00 pm. Solved by 326 members at time of mirroring.

Why this is useful

Optimization. A genuine objective is optimised over a choice set - the same shape as calibration and optimal-execution problems (Phases 10, 16).

We classify relevance honestly - not every Euler problem is a trading application.

Learning mode

Pick how much scaffolding you want. Your choice is remembered per problem.

Scratchpad

Mathematical notes, formulas, pseudocode, hypotheses, complexity notes. Saved automatically with your progress.

Python workbench

Tier C - reduced scale in browser; full scale in notebook
Browser runs a reduced, clearly-labelled educational scale; the original scale is provided in a local notebook.

Real Python (Pyodide) in a sandboxed Web Worker - no network, no filesystem, no DOM access. Ctrl/Cmd+Enter runs. Escape leaves the editor. Stop terminates the worker.

Python runtime not loaded (it boots on first run - a one-time local load).

Check your answer

Answers are checked against a salted hash held in a separate file - not printed in this page. This prevents accidental spoilers; it is not cryptographic protection (see the build notes).

Progressive hints

Confidence

Low confidence schedules this problem for spaced review, even if you solved it.

Reference solution

Spoiler
The complete original explanation (interpretation, naive approach, insight, proof, complexity, Python implementation, tests, common mistakes, alternatives) is hidden and lazy-loaded. Reveal it only after a meaningful attempt - the struggle is where the learning happens.