Project Euler Lab - Problem 321

#321 - Swapping Counters

● AdvancedOfficial difficulty: 32%PointsTier C - reduced scale in browser; full scale in notebookNot viewed
↖ Euler Lab

A horizontal row comprising of \(2n + 1\) squares has \(n\) red counters placed at one end and \(n\) blue counters at the other end, being separated by a single empty square in the centre. For example, when \(n = 3\).

0321_swapping_counters_1.gif

A counter can move from one square to the next (slide) or can jump over another counter (hop) as long as the square next to that counter is unoccupied.

0321_swapping_counters_2.gif

Let \(M(n)\) represent the minimum number of moves/actions to completely reverse the positions of the coloured counters; that is, move all the red counters to the right and all the blue counters to the left.

It can be verified \(M(3) = 15\), which also happens to be a triangle number.

If we create a sequence based on the values of \(n\) for which \(M(n)\) is a triangle number then the first five terms would be:
\(1\), \(3\), \(10\), \(22\), and \(63\), and their sum would be \(99\).

Find the sum of the first forty terms of this sequence.

This problem is taken from Project Euler, Problem 321.
Problem text © Project Euler, licensed under CC BY-NC-SA 4.0. Original: projecteuler.net/problem=321. Published Sunday, 23rd January 2011, 01:00 am. Solved by 2,039 members at time of mirroring.

Why this is useful

Mathematical Foundation. Exact integer reasoning and algorithmic efficiency. Foundational rigour and computational discipline rather than a direct trading application.

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.