Project Euler Problem 335

Whenever Peter feels bored, he places some bowls, containing one bean each, in a circle.

Project Euler Problem 335

Solution

Answer: 5032316

Let

$$n = 2^k+1$$

and define $M(n)$ as the number of moves needed to return to the starting configuration of $n$ bowls, each initially containing one bean.

The key challenge is to understand the structure of $M(2^k+1)$, then sum it efficiently up to $k=10^{18}$.


1. Mathematical analysis

Step 1: Empirical structure

If we simulate the process for small $k$:

$$\begin{aligned} M(2)&=2\ M(3)&=5\ M(5)&=15\ M(9)&=53\ M(17)&=207\ M(33)&=845 \end{aligned}$$

The problem statement gives:

$$M(5)=15,\qquad M(100)=10920$$

Now consider the values

$$M(2^k+1)-2^{k+1}$$

for small $k$:

$$0,1,7,37,175,781,3367,\dots$$

This sequence matches

$$4^k-3^k$$

exactly, giving the closed form

$$M(2^k+1)=4^k-3^k+2^{k+1}.$$

We verify:

  • $k=2$: $16-9+8=15$
  • $k=3$: $64-27+16=53$
  • $k=4$: $256-81+32=207$

All match.

Thus:

$$M(2^k+1)=4^k-3^k+2^{k+1}.$$

This identity is the crucial insight.


Step 2: Sum over $k=0$ to $10^{18}$

We want

$$S=\sum_{k=0}^{10^{18}} M(2^k+1).$$

Substitute the formula:

$$S = \sum_{k=0}^{N} (4^k-3^k+2^{k+1}), \qquad N=10^{18}.$$

Split into geometric sums:

$$S = \sum_{k=0}^{N}4^k - \sum_{k=0}^{N}3^k + 2\sum_{k=0}^{N}2^k.$$

Using

$$\sum_{k=0}^{N}r^k=\frac{r^{N+1}-1}{r-1},$$

we get

$$S = \frac{4^{N+1}-1}{3} - \frac{3^{N+1}-1}{2} + 2(2^{N+1}-1).$$

We only need this modulo

$$7^9 = 40353607.$$

Since 2 and 3 are coprime to $7^9$, modular inverses exist.


2. Python implementation

MOD = 7**9
N = 10**18

# Modular inverses
inv2 = pow(2, -1, MOD)
inv3 = pow(3, -1, MOD)

# Geometric sums modulo MOD
sum_4 = (pow(4, N + 1, MOD) - 1) * inv3
sum_3 = (pow(3, N + 1, MOD) - 1) * inv2
sum_2 = 2 * (pow(2, N + 1, MOD) - 1)

answer = (sum_4 - sum_3 + sum_2) % MOD

print(answer)

3. Code walkthrough

Modulus

MOD = 7**9

The problem asks for the result modulo $7^9$.


Fast modular exponentiation

pow(base, exponent, MOD)

Python computes huge powers efficiently using repeated squaring.

For example:

pow(4, 10**18 + 1, MOD)

takes logarithmic time.


Modular division

We need to divide by 2 and 3 in modular arithmetic.

Instead of ordinary division, we multiply by inverses:

inv2 = pow(2, -1, MOD)
inv3 = pow(3, -1, MOD)

because

$$a/b \pmod m = a\cdot b^{-1}\pmod m.$$


Small verification

For $k=2$:

$$M(5)=4^2-3^2+2^3 =16-9+8 =15,$$

matching the problem statement.

For $x=100$, direct simulation gives

$$M(100)=10920,$$

consistent with the problem statement.


4. Final verification

The expression is dominated by geometric growth, but we only need a residue modulo $7^9$, so fast modular exponentiation is appropriate.

The computation gives:

$$S \equiv 5032316 \pmod{7^9}.$$

Answer: 5032316