Spiral Primes¶
It's the return of the Ulam spiral from problem 28 (this time we're going counter-clockwise, but that doesn't actually affect much).
We can handle this problem with a couple of easy-to-derive formulas. First, for a spiral with side length $n$ (note that $n$ must be odd), the number of diagonal entries is $2n-1$. Furthermore, the outermost diagonal entries will be $n^2$, $n^2 - (n-1)$, $n^2 - 2(n-1)$, and $n^2 - 3(n-1)$.
With these facts, we can just iterate over odd values of $n$ and calculate the four outermost diagonal entries. We'll keep a running total $p$ of how many primes we see and stop when $\frac{p}{2n-1} < 0.1$.
def diagonal(n, k): return n^2 - k*(n-1)
from itertools import count
p = 0
for n in count(3, 2):
for k in range(0, 4):
if is_prime(diagonal(n, k)):
p += 1
if p / (2*n - 1) < 0.1:
break
n
26241
Relevant sequences¶
Copyright (C) 2025 filifa¶
This work is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license and the BSD Zero Clause license.