Click to See Complete Forum and Search --> : The most optimal PHP prime spiral generator yet


Mgccl
05-09-2007, 07:21 PM
Prime spirals are always fun to watch(not...) and pretty brain hurting to implement. After 2 trials, Chao successfully created by far the fastest PHP prime spiral generator(for a 200*200 image, it's 20 times faster than the original)...
I challenge anyone to write a script that beat this one's speed

http://webdevlogs.com/2007/05/07/the-most-optimal-php-prime-spiral-generator-yet

http://webdevlogs.com/files/primespiral500.png

$size = 500;
$prime = esprime($size*$size);
$image = imagecreate($size,$size);
imagecolorallocate($image,255,255,255);
$color = imagecolorallocate($image,0,0,0);
$size2=$size/2;
$n = 2;$t = true;$sn=4;
$midu=2;$midl=4;$midd=6;$midr=8;
while($n<$size){
if($prime[0]<=$sn){
$p = array_shift($prime);
if($t){//even
if($p <= $sn-$n){
$x = $n/2;
$y = $midu - $p;
}else{
$x = $midl -$p;
$y = -$n/2;
}
}else{//odd
if($p <= $sn-$n){
$x = (-$n/2)+0.5;
$y = $p - $midd;
}else{
$x = $p - $midr;
$y = ($n/2)-0.5;
}
}
imagesetpixel($image,$x+$size2,$y+$size2,$color);
}else{
++$n;
$sn = $n * $n;
$t = !$t;
if($t){
$midu = $sn-$n*1.5+1;
$midl = $sn-$n*0.5+1;
}else{
$midd = $sn-$n*1.5+1.5;
$midr = $sn-$n*0.5+0.5;
}
}
}
header("Content-type: image/png");
imagepng($image);

Weedpacket
05-10-2007, 07:52 AM
esprime()?

Weedpacket
05-11-2007, 04:53 AM
Another thing; if it's speed you're after then using integer arithmetic instead of floating point might gain you a few milliseconds. (Remember, all division in PHP is done with floating point).

Mgccl
05-12-2007, 01:32 AM
I made a super good thing that increase this script by 650 times!
http://webdevlogs.com/2007/05/11/array-shift-is-slower-than-i-thought

btw esprime() is just a prime counting function made by me, you can find it here
http://webdevlogs.com/2007/03/14/string-is-better-than-array-memory-exhausting-calculation-special-case-return-all-prime-n