ulam.py

Created by gianfranco-oddenino

Created on March 07, 2025

523 Bytes

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)

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.