#include <stdio.h>
#define NUMPRIMES 1000
static int prime[NUMPRIMES];

int nextprime( n )    /* Return next prime number >= n */
int n;
{
   int i, number;

   number = n;
   if (number > 3)
   {
      if (number % 2 == 0) ++number;
      i = 1;
      while ( prime[i]*prime[i] <= number )
      {
         if ( number % prime[i] == 0 )
         {
            number += 2;
            i = 1;
         }
         else
         {
            ++i;
         }
      }/*end while*/
   }/*end if (number>3)*/
   return(number);
}

main()
{
   int i;
   FILE *output_file;
   output_file = fopen("primes.lis","w");
   if ( output_file == (FILE *) NULL )
   {
      printf("*** output file could not be created ***\n");
      return;
   }
   prime[0] = 2;
   prime[1] = 3;
   for ( i=2; i < NUMPRIMES; ++i )
   {
      prime[i] = nextprime( prime[i-1]+1 );
   }
   for ( i=0; i < NUMPRIMES; ++i )
   {
      fprintf( output_file, "%d\n", prime[i] );
   }
   fclose( output_file );
   printf("Output file is PRIMES.LIS");
}

Back