I've written a simple piece of code to display the Ulam Spiral (
http://en.wikipedia.org/wiki/Ulam_spiral)
Nothing fancy: the algorithm draws the spiral pixel by pixel, and checks if each new number is a prime - if so, it'll draw a point on that pixel.
In the first line, int dim = 200 sets the matrix to 200x200. If I set this value to anything over 500 in my MacBookPro, the sketch takes forever to run - I've never seen it compile when set to 1000.
Is this just the way it is, or is there a better, less processor intensive way to check if a number is prime? Commenting out the call to checkNumber() makes the code run in a jiffy, so the problem must be within this function alright.
Thanks in advance!
Nothing fancy: the algorithm draws the spiral pixel by pixel, and checks if each new number is a prime - if so, it'll draw a point on that pixel.
In the first line, int dim = 200 sets the matrix to 200x200. If I set this value to anything over 500 in my MacBookPro, the sketch takes forever to run - I've never seen it compile when set to 1000.
Is this just the way it is, or is there a better, less processor intensive way to check if a number is prime? Commenting out the call to checkNumber() makes the code run in a jiffy, so the problem must be within this function alright.
Thanks in advance!
- int dim = 200;
int matrixDim = dim-1;
int centerPoint = ((matrixDim-1)/2);
int cellCount = 1;
void setup() {
size(dim,dim);
background(255);
int currentPosX = centerPoint;
int currentPosY = centerPoint;
int highestVal=matrixDim*matrixDim;
float diagVal;
//start at center point, defined as (matrixDim-1/2, matrixDim-1/2);
//in an odd dimension matrix. such as 7x7, center point is (3,3);
point (centerPoint,centerPoint);
//starting at the center point, the algorithm for drawing the Ulam spiral is as follows:
//for a step N
// Right 2N-1 Steps
// then Up 2N-1 Steps
// then Left 2N Steps
// then Down 2N
for (int counter=1;counter<matrixDim;counter++) {
int RUCounter = (2*counter)-1;
int LDCounter = 2*counter;
for (int i=0;i<RUCounter;i++) {
currentPosX++;
cellCount++;
checkCell(currentPosX,currentPosY,cellCount);
}
for (int i=0;i<RUCounter;i++) {
currentPosY++;
cellCount++;
checkCell(currentPosX,currentPosY,cellCount);
}
for (int i=0;i<LDCounter;i++) {
currentPosX--;
cellCount++;
checkCell(currentPosX,currentPosY,cellCount);
}
for (int i=0;i<LDCounter;i++) {
currentPosY--;
cellCount++ ;
checkCell(currentPosX,currentPosY,cellCount);
}
}
}
void checkCell(int posX, int posY,int number) {
if (checkNumber(number)) {
point(posX,posY);
}
}
boolean checkNumber(int n) {
boolean isPrime = false;
for (int i=2;i<n;i++) {
if (n%i== 0) {
isPrime=false;
break;
}
else {
isPrime=true;
}
}
return isPrime;
}
1