Forum Discussion
Patrick2788
Jul 18, 2023Silver Contributor
Formula Challenge: The most efficient way to generate a Number Spiral (Ulam spiral) ?
The goal: Ulam spiral - Wikipedia The trick is creating a function capable of producing the largest matrix of numbers possible (this may rule out the recursive approach). The approach ...
Patrick2788
Aug 31, 2025Silver Contributor
One way to speed up the spiral is to use thunks/lazy evaluation all the way down:
SpiralĪ» = LAMBDA(n, [start_at],
LET(
start_at, IF(ISOMITTED(start_at), 1, start_at),
i, LAMBDA(SEQUENCE(n * 2 + 1, , n, -1)),
j, LAMBDA(SEQUENCE(, n * 2 + 1, -n, 1)),
x, LAMBDA(j() * SEQUENCE(n * 2 + 1, , 1, 0)),
y, LAMBDA(i() * SEQUENCE(, n * 2 + 1, 1, 0)),
a_, LAMBDA((ABS(x()) > ABS(y())) * (x() > 0)),
b_, LAMBDA((ABS(x()) > ABS(y())) * (x() <= 0)),
c_, LAMBDA((ABS(x()) <= ABS(y())) * (y() > 0)),
d_, LAMBDA((ABS(x()) <= ABS(y())) * (y() <= 0)),
a, LAMBDA(4 * x() ^ 2 - 3 * x() + y()),
b, LAMBDA(4 * x() ^ 2 - x() - y()),
c, LAMBDA(4 * y() ^ 2 - y() - x()),
d, LAMBDA(4 * y() ^ 2 - 3 * y() + x()),
result, start_at + IF(a_(), a(), IF(b_(), b(), IF(c_(), c(), d()))),
result
)
);
This generates a spiral with 51,854,401 elements in about 78 seconds.