xxxxxxxxxx
97
// 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;
// Scale / resolution
let stepSize = 13;
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(800, 800);
// 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(Infinity);
for(let i = 0; i < totalSteps/4; i++) {
fill(noise(x) * 255, noise(x, y) * 255, noise(y) * 255);
stroke(noise(x) * 255, noise(x, y) * 255, noise(y) * 255);
// If prime draw circle
if (isPrime(step)) {
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) {
noLoop();
}
}
}