This script draws the Ulam spiral of the prime numbers in the range from 1 to 4096.
import matplotlib.pyplot as plt def is_prime(n): if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def plot(n): x, y, dx, dy = 0, 0, 1, 0 px, py = [], [] for i in range(1, n + 1): if is_prime(i): px.append(x) py.append(y) x += dx y += dy if x == y or (x < 0 and y == -x) or (x > 0 and y == 1 - x): dx, dy = -dy, dx plt.axis((-32, 32, -22, 22)) plt.scatter(px, py) plt.show() plot(4096)