xxxxxxxxxx
112
// The Prime Spiral (aka Ulam Spiral)
// The Coding Train / Daniel Shiffman
// https://thecodingtrain.com/CodingChallenges/167-prime-spiral.html
// https://youtu.be/a35KWEjRvc0
// Prime Spiral: https://editor.p5js.org/codingtrain/sketches/0Ud-XsaYb
// Number Spiral: https://editor.p5js.org/codingtrain/sketches/Zs65bV-Al
// Prime vs Random Spiral: https://editor.p5js.org/codingtrain/sketches/3np1hBlXD
// Shapes and Color: https://editor.p5js.org/codingtrain/sketches/mCvvSKpZ5
// Prime Spiral 3D: https://editor.p5js.org/codingtrain/sketches/-eX078HZ5
// State of spiral
let x, y;
let px, py;
let step = 1;
let state = 0;
let numSteps = 1;
let turnCounter = 1;
let iterationsPerLoop = 20;
// Scale / resolution
let stepSize = 5;
let totalSteps;
// Function to test if number is prime
function isPrime(value) {
if (value == 1) return false;
for (let i = 2; i <= sqrt(value); i++) {
if (value % i == 0) {
return false;
}
}
return true;
}
function setup() {
createCanvas(500, 500);
// set up spiral
const cols = width / stepSize;
const rows = height / stepSize;
totalSteps = cols * rows;
x = width / 2;
y = height / 2;
px = x;
py = y;
background(0);
}
function draw() {
frameRate(300);
spiral();
}
function spiral() {
let r = 0;
let g = 0;
let b = 0;
while (true) {
for(i = 0; i < iterationsPerLoop; i++) {
// If prime draw circle
r=random(1,255);
g=random(1,255);
b=random(1,255);
stroke(r,g,b)
fill(r,g,b);
if (isPrime(step)) {
stroke(r,g,b);
fill(r,g,b);
circle(x, y, stepSize * 0.5);
}
// Connect current to previous with a line
line(x, y, px, py);
px = x;
py = y;
// Move according to state
switch (state) {
case 0:
x += stepSize;
break;
case 1:
y -= stepSize;
break;
case 2:
x -= stepSize;
break;
case 3:
y += stepSize;
break;
}
// Change state
if (step % numSteps == 0) {
state = (state + 1) % 4;
turnCounter++;
if (turnCounter % 2 == 0) {
numSteps++;
}
}
step++;
// Are we done?
if (step > totalSteps) {
break;
}
}
}
}