xxxxxxxxxx
118
// Ulam Prime Spiral
// https://youtu.be/a35KWEjRvc0
// cmd + / = comments
//----------------------------------
// CODING CHALLENGE 167 -- PRIME SPIRAL
//----------------------------------
//--- global variables
let x, y;
let px, py;
let step = 1;
let state = 0;
let numSteps = 1; // initial number
let turnCounter = 1;
// 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;
}
//-------------------- setup
function setup() {
// createCanvas(700, 700);
createCanvas(windowWidth, windowHeight);
//background(0);
// 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);
}
//-------------------- draw
function draw() {
// if prime, draw circle
if (isPrime(step)) {
fill('#00ff009'); // purple 66ff99
stroke('#00ff00');
circle(x, y, stepSize * 0.5);
}
// connect current to previous line
line(x, y, px, py);
px = x;
py = y;
// switch statement 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 == 0 its even
if (step % numSteps == 0) {
state = (state + 1) % 4;
turnCounter++;
if (turnCounter % 2 == 0) {
numSteps++;
}
}
step++;
// check if done
if (step > totalSteps) {
noLoop();
}
}// draw