 |
Author |
Topic: Prime (Read 766 times) |
|
rgovostes
|
Prime
« on: Feb 3rd, 2004, 1:32am » |
|
These give a visualization of prime numbers without having to check each number for being prime. The first displaces the results in a grid, with dark squares representing prime numbers, and grey ones representing composite (non-prime) numbers. The second is a bit faster, and instead just use a single pixel for each number. Neither has been optimized much. I could check to see if the number being tested is greater than the square root of the maximum number, and if so stop, but I do not think this would speed it up much if at all. Code:// Prime v1, Feb 02 '04 // by Ryan Govostes int cols = 23; // Prime int rows = 30; int sizex = 20; int sizey = 20; int n = 1; int[] isPrime = new int[(cols * rows) + 1]; void setup() { size((cols * sizex) + 1, (rows * sizey) + 1); stroke(50); isPrime[1] = 2; } void loop() { int v = n; while(v <= (cols * rows) && isPrime[v] > 0) { v ++; } if (v <= (cols * rows)) { isPrime[v] = 2; for(int x = (v * 2); x <= (cols * rows); x += v) { isPrime[x] = 1; } n = v; } background(255); for(int i = 0; i < (cols * rows); i ++) { if (isPrime[i + 1] == 0) { noFill(); } // nil else if (isPrime[i + 1] == 1) { fill(200); } // not prime else if (isPrime[i + 1] == 2) { fill(100); } // prime rect((i % cols) * sizex, floor(i / cols) * sizey, sizex, sizey); } } |
| Code:// Prime Pixels v1, Feb 02 '04 // by Ryan Govostes int n = 1; color nil, prime, composite; void setup() { nil = color(255, 255, 255); prime = color(100, 100, 100); composite = color(200, 200, 200); size(200, 200); background(nil); pixels[0] = prime; } void loop() { int z; while(n < (width * height) && pixels[n - 1] != nil) { n ++; } if (n < (width * height)) { pixels[n - 1] = prime; //z = 0; for(int x = (n * 2); x < (width * height); x += n) { pixels[x - 1] = composite; // z ++; } //println("Discovered " + z + " composite numbers."); } } |
|
|
« Last Edit: Feb 5th, 2004, 12:53am by rgovostes » |
|
|
|
|
|