James Cassell's Blog

Sunday, August 21, 2005

Someone requested that I post the code for my Prime number calculator, so I will do so here. It is a function that will output to the page all of the prime numbers between 2 and the number that is given as input.

function prime($count)
{
 if($count>10000) #when changing this also change line 18
  return(0);
 $length = 1;
 /*unsigned int x, test;*/
 $stored[0] = 2;
 printf("%d\n",$stored[0]);
 $test = 3;
 while($test <= $count)
 {
  for($x=0;$x<$length;$x++)
  {
   if(!($test % $stored[$x]))
    break;
   else if($stored[$x] * $stored[$x] > $test)
   {
    if($length < 102)# change "102" to a number slightly greater than the square root of number in line 3
     $stored[$length++] = $test;
    printf("%u\n",$test);
    break;
   }
  }
  $test+=2;
 }
 return(1);
}

1 Comments:

  • Thanks for your code, i love that kind of things. (i wrote a "PI" counter my self)

    Glad i found this blog, think i'm going to visit it a lot.

    (Sorry for my english, my native is russian)

    By Anonymous Vladson, at 22 August, 2005 20:26  

Post a Comment

<< Home