I promised in my last post about make something faster for create the basic prime spiral graph, and I finally made it. 
I modified Christopher David Lane's spiral generator class by adding a method of jump though primeless gaps.Although I made one myself but it is too confusing to read.

Behold, this generates a prime number spiral in 2.5 seconds on my machine!
$n = 200;
$image = imagecreate($n,$n);
imagecolorallocate($image, 255,255,255);
$color = imagecolorallocate($image, 0,0,0);
$sn=$n*$n;
$prime = esprime($sn);
$y=$x=$n/2;
$color2 = imagecolorallocate($image, 255,0,0);
imagesetpixel($image,$x,$y,$color2);
$remain = 2;
$distance = 1;
$direction = 1;
for ($count = 2; $count <= $sn; ++$count) {
if (--$remain == 0) {
switch ($direction) {
case 0: $distance++; $direction = 3; break;
case 2: $distance++;
default: $direction--; break;
}
$remain = $distance;
}
switch ($direction) {
case 3: --$x; break;
case 1: ++$x; break;
case 0: --$y; break;
case 2: ++$y; break;
}
if($prime[0] == $count){
array_splice($prime, 0, 1);
imagesetpixel($image,$x,$y,$color);
}
if(isset($prime[0])){
if($prime[0]-$count+1<$remain){
switch ($direction) {
case 3: $x-=$prime[0]-$count-1; break;
case 1: $x+=$prime[0]-$count-1; break;
case 0: $y-=$prime[0]-$count-1; break;
case 2: $y+=$prime[0]-$count-1; break;
}
$remain -= $prime[0]-$count-1;
$count +=$prime[0]-$count-1;
}elseif($prime[0]-$count+1>=$remain){
switch ($direction) {
case 3: $x-=$remain-1; break;
case 1: $x+=$remain-1; break;
case 0: $y-=$remain-1; break;
case 2: $y+=$remain-1; break;
}
$count +=$remain-1;
$remain = 1;
}
}
}
header("Content-type: image/png");
imagepng($image);
Bookmark/Search this post with:
Post new comment