All Euler problems
Project Euler

Spiral Primes

Starting with 1 and spiralling anticlockwise, a square spiral with side length s is formed. The diagonals of this spiral contain certain values. What is the side length of the square spiral for whi...

Source sync Apr 19, 2026
Problem #0058
Level Level 02
Solved By 45,052
Languages C++, Python
Answer 26241
Length 573 words
modular_arithmeticnumber_theoryanalytic_math

Problem Statement

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

Starting with \(1\) and spiralling anticlockwise in the following way, a square spiral with side length \(7\) is formed. \[ \begin {tabular}{ccccccc} \textcolor {red}{37} & 36 & 35 & 34 & 33 & 32 & \textcolor {red}{31} \\ 38 & \textcolor {red}{17} & 16 & 15 & 14 & \textcolor {red}{13} & 30 \\ 39 & 18 & \textcolor {red}{5} & 4 & \textcolor {red}{3} & 12 & 29 \\ 40 & 19 & 6 & 1 & 2 & 11 & 28 \\ 41 & 20 & \textcolor {red}{7} & 8 & 9 & 10 & 27 \\ 42 & 21 & 22 & 23 & 24 & 25 & 26 \\ \textcolor {red}{43} & 44 & 45 & 46 & 47 & 48 & 49 \\ \end {tabular} \] It is interesting to note that the odd squares lie along the bottom right diagonal, but what is more interesting is that \(8\) out of the \(13\) numbers lying along both diagonals are prime; that is, a ratio of \(8/13 \approx 62\%\).

If one complete new layer is wrapped around the spiral above, a square spiral with side length \(9\) will be formed. If this process is continued, what is the side length of the square spiral for which the ratio of primes along both diagonals first falls below \(10\%\)?

Problem 58: Spiral Primes

Mathematical Development

Definition 1 (Ulam Spiral Layers). The spiral is organized into layers indexed by k=0,1,2,k = 0, 1, 2, \ldots, where layer k=0k = 0 is the center (containing only the value 1) and layer k1k \geq 1 has side length sk=2k+1s_k = 2k + 1.

Theorem 1 (Corner Values). For layer k1k \geq 1 (side length s=2k+1s = 2k + 1), the four diagonal corner values are:

c1(k)=4k22k+1(top-right),c2(k)=4k2+1(top-left),c3(k)=4k2+2k+1(bottom-left),c4(k)=(2k+1)2=4k2+4k+1(bottom-right).\begin{aligned} c_1(k) &= 4k^2 - 2k + 1 &\quad &\text{(top-right)}, \\ c_2(k) &= 4k^2 + 1 &\quad &\text{(top-left)}, \\ c_3(k) &= 4k^2 + 2k + 1 &\quad &\text{(bottom-left)}, \\ c_4(k) &= (2k+1)^2 = 4k^2 + 4k + 1 &\quad &\text{(bottom-right)}. \end{aligned}

Proof. The bottom-right corner of layer kk is the last number placed in that layer, namely (2k+1)2(2k+1)^2. Moving counterclockwise along the outermost ring, consecutive corners are separated by s1=2ks - 1 = 2k positions. Thus, stepping back from (2k+1)2(2k+1)^2:

Bottom-left:(2k+1)22k=4k2+4k+12k=4k2+2k+1,Top-left:(2k+1)24k=4k2+1,Top-right:(2k+1)26k=4k22k+1.\begin{aligned} \text{Bottom-left:} & \quad (2k+1)^2 - 2k = 4k^2 + 4k + 1 - 2k = 4k^2 + 2k + 1, \\ \text{Top-left:} & \quad (2k+1)^2 - 4k = 4k^2 + 1, \\ \text{Top-right:} & \quad (2k+1)^2 - 6k = 4k^2 - 2k + 1. \end{aligned}

\square

Lemma 1 (Bottom-Right Corner is Always Composite). For k1k \geq 1, c4(k)=(2k+1)2c_4(k) = (2k+1)^2 is composite.

Proof. (2k+1)2(2k+1)^2 has the nontrivial factor 2k+132k + 1 \geq 3, so it is a perfect square greater than 1, hence composite. \square

Theorem 2 (Diagonal Element and Prime Counts). After processing layers 11 through kk:

(i) The total number of diagonal elements is T(k)=4k+1T(k) = 4k + 1 (including the center value 1).

(ii) The number of prime diagonal elements is

P(k)=j=1ki=131[ci(j) is prime],P(k) = \sum_{j=1}^{k} \sum_{i=1}^{3} \mathbf{1}\bigl[c_i(j) \text{ is prime}\bigr],

where 1[]\mathbf{1}[\cdot] is the indicator function. The fourth corner c4(j)c_4(j) is excluded by Lemma 1.

Proof. (i) Layer 0 contributes 1 element. Each subsequent layer contributes 4 corners. After kk layers: 1+4k1 + 4k. (ii) The center value 1 is not prime. At each layer jj, at most 3 of the 4 corners can be prime (since c4c_4 is always composite). \square

Theorem 3 (The Ratio P(k)/T(k)0P(k)/T(k) \to 0). The prime ratio along the diagonals tends to zero as kk \to \infty.

Proof. The corner values at layer kk are Θ(k2)\Theta(k^2). By the Prime Number Theorem, the probability that a random integer near NN is prime is asymptotically 1/lnN1/\ln N. For N=Θ(k2)N = \Theta(k^2), this probability is 1/(2lnk)\sim 1/(2 \ln k).

The expected number of primes contributed by layer jj is therefore approximately 3/(2lnj)3/(2 \ln j), and

P(k)j=2k32lnj3k2lnkP(k) \approx \sum_{j=2}^{k} \frac{3}{2 \ln j} \sim \frac{3k}{2 \ln k}

by the integral estimate j=2k1/lnjk/lnk\sum_{j=2}^{k} 1/\ln j \sim k/\ln k (a consequence of the prime number theorem applied to the sum). The ratio is

P(k)4k+13k/(2lnk)4k=38lnkk0.\frac{P(k)}{4k + 1} \approx \frac{3k/(2 \ln k)}{4k} = \frac{3}{8 \ln k} \xrightarrow{k \to \infty} 0. \qquad \square

Corollary 1 (Existence of Threshold Crossing). For any ε>0\varepsilon > 0, there exists a finite k0k_0 such that P(k0)/T(k0)<εP(k_0)/T(k_0) < \varepsilon. The problem asks for s=2k0+1s = 2k_0 + 1 where ε=0.10\varepsilon = 0.10.

Lemma 2 (Primality Testing Bound). To test whether n=ci(k)n = c_i(k) is prime by trial division, it suffices to check divisors up to n2k+1\lfloor\sqrt{n}\rfloor \leq 2k + 1.

Proof. If nn is composite, it has a factor at most n\sqrt{n}. Since ci(k)(2k+1)2c_i(k) \leq (2k+1)^2, we have ci(k)2k+1\sqrt{c_i(k)} \leq 2k + 1. \square

Proposition 1 (Rough Estimate via PNT). Setting 3/(8lnk)=0.103/(8 \ln k) = 0.10 gives lnk=3.75\ln k = 3.75, hence k42k \approx 42, corresponding to side length s85s \approx 85. This is a very rough lower bound; the actual answer is much larger because the PNT approximation overestimates the prime count for small to moderate kk.

Editorial

We process the spiral layer by layer. For each new side length s=2k+1s = 2k+1, only the three non-square corner values need to be tested for primality, because the fourth corner is always (2k+1)2(2k+1)^2 and therefore composite. Maintaining the cumulative number of diagonal entries and diagonal primes allows the prime ratio to be updated after each layer, and the first side length for which this ratio falls below 10% is returned.

Pseudocode

Algorithm: Spiral Side Length at Which the Prime Ratio Falls Below One Tenth
Require: Primality testing for the diagonal corner values of the spiral.
Ensure: The first odd side length for which the ratio of prime numbers on the diagonals is less than 10%.
1: Initialize prime_count ← 0, diagonal_count ← 1, and k ← 0.
2: Repeat:
3:     Set k ← k + 1 and s ← 2k + 1, then form the three non-square corner values on the layer of side length s.
4:     Test those three corners for primality, update prime_count accordingly, and set diagonal_count ← diagonal_count + 4.
5:     If prime_count / diagonal_count < 0.1, return s.

Complexity Analysis

Theorem 4 (Time Complexity). Let KK denote the final layer index (so s=2K+1s = 2K + 1). With trial division, the algorithm runs in O(K2)O(K^2) time. With Miller-Rabin primality testing, the time reduces to O(Klog2K)O(K \log^2 K).

Proof. At each layer kk, we test 3 numbers for primality. Each corner value n(2K+1)2n \leq (2K+1)^2 has n=O(K)\sqrt{n} = O(K). Trial division with the 6k±16k \pm 1 optimization tests O(K/lnK)O(K/\ln K) candidates per number in the worst case, but the dominant cost across all KK layers is k=1KO(k)=O(K2)\sum_{k=1}^{K} O(k) = O(K^2), since the trial division bound grows with kk.

With deterministic Miller-Rabin using a fixed set of witnesses, each primality test costs O(log2n)=O(log2K)O(\log^2 n) = O(\log^2 K), giving total cost 3KO(log2K)=O(Klog2K)3K \cdot O(\log^2 K) = O(K \log^2 K).

For the answer K=13120K = 13120 (side length s=26241s = 26241), O(K2)1.7×108O(K^2) \approx 1.7 \times 10^8, which is feasible. \square

Space: O(1)O(1) — only a constant number of integer variables are maintained.

Answer

26241\boxed{26241}

Code

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

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

typedef long long ll;

// Modular multiplication using __int128 to avoid overflow.
ll mulmod(ll a, ll b, ll m) {
    return (__int128)a * b % m;
}

// Fast modular exponentiation: base^exp mod mod.
ll powmod(ll base, ll exp, ll mod) {
    ll result = 1;
    base %= mod;
    while (exp > 0) {
        if (exp & 1) result = mulmod(result, base, mod);
        base = mulmod(base, base, mod);
        exp >>= 1;
    }
    return result;
}

// Single round of Miller-Rabin with witness a.
bool millerRabin(ll n, ll a) {
    if (n % a == 0) return n == a;
    ll d = n - 1;
    int r = 0;
    while (d % 2 == 0) { d /= 2; r++; }
    ll x = powmod(a, d, n);
    if (x == 1 || x == n - 1) return true;
    for (int i = 0; i < r - 1; i++) {
        x = mulmod(x, x, n);
        if (x == n - 1) return true;
    }
    return false;
}

// Deterministic primality test for n < 3.2 * 10^18.
bool isPrime(ll n) {
    if (n < 2) return false;
    if (n < 4) return true;
    if (n % 2 == 0 || n % 3 == 0) return false;
    for (ll a : {2, 3, 5, 7, 11, 13}) {
        if (!millerRabin(n, a)) return false;
    }
    return true;
}

int main() {
    int primeCount = 0;
    int totalDiag = 1;  // center = 1

    for (ll k = 1; ; k++) {
        ll s = 2 * k + 1;
        ll sq = s * s;
        totalDiag += 4;

        // Three non-square corners: skip (2k+1)^2 by Lemma 1
        if (isPrime(sq - (s - 1)))     primeCount++;
        if (isPrime(sq - 2 * (s - 1))) primeCount++;
        if (isPrime(sq - 3 * (s - 1))) primeCount++;

        if (primeCount > 0 && 10 * primeCount < totalDiag) {
            cout << s << endl;
            return 0;
        }
    }
    return 0;
}