primes.c

a lifetime ago, my friend lester and i were talking about computer programming. he was interested but did not know the basic concepts, and he asked me if i could show him a program and explain it to him. when i got home i found a semi-practical C program i had hacked together earlier and put comments into it. when we next met i gave him a printout and a floppy, and explained every line. he asked all the right questions and picked it up very quickly. he spent the next half hour studying the printout, asking the occasional question. i do not know if he got the programming bug, as we did not get a chance for a follow-up.

lester was a highly intelligent considerate person with a quirky sense of humor. i miss him terribly and think about him often. happy birthday, lester.

// ansi compliant prime number generator written by r 10/1998
// quick & dirty (hard-coded array size, no bounds checking, etc.)

#include <stdio.h>
#include <stdlib.h>

signed int main(void)
{
   signed int x,y,pcnt,primes[10000];
   div_t z;

   puts("calculating primes - please wait");
   primes[0]=2;  // store first prime
   primes[1]=3;  // store second prime
   pcnt=1;  // number of primes in array (starting at count 0 of course)
   for(x=5;x<20000;x+=2)  // check numbers up to 20000 for prime, skipping evens
   {
      for(y=1;y<=pcnt;y++)  // y is the divisor
      {
         z=div(x,primes[y]);  // do the math
         if(!z.rem)  // if there is no remainder,
         {
            break;  // then this is not a prime
         }
      }
      if(y>pcnt)  // if we didn't break out above,
      {
         primes[++pcnt]=x;  // then we have a prime, so store it and inc counter
      }
   }
   for(x=0;x<=pcnt;x++)  // we are done now; this loop prints out found primes
   {
      printf("%4d: %d\n",x+1,primes[x]);
   }
   return 0;  // fin
}

Leave a Reply