//===================================================== file = prime2.c =====
//=  Program to find the first N prime numbers                              =
//===========================================================================
//=  Build: bcc32 prime1.c, gcc prime1.c -lm                                =
//=-------------------------------------------------------------------------=
//=  Execute: summary1 < in.dat                                             =
//=-------------------------------------------------------------------------=
//=  Author: Kenneth J. Christensen                                         =
//=          University of South Florida                                    =
//=          WWW: http://www.csee.usf.edu/~christen                         =
//=          Email: christen@csee.usf.edu                                   =
//=-------------------------------------------------------------------------=
//=  History: KJC (08/21/00) - Genesis                                      =
//===========================================================================

//----- Include files -------------------------------------------------------
#include <stdio.h>                 // Needed for printf() and feof()
#include <stdlib.h>                // Needed for atoi()
#include <math.h>                  // Needed for pow()

//===== Main program ========================================================
void main(int argc, char *argv[])
{
  unsigned int i, count, test_val, max, *prime, N;

  N = atoi(argv[1]);
  prime = (int *) malloc(N * sizeof(int));
  if (prime == NULL)
  {
    printf("ERROR - malloc() failed... bail-out \n");
    return;
  }

  test_val = 3;
  count = 2;
  prime[0] = 2;
  prime[1] = 3;
  prime[2] = 5;
  while(1)
  {
top:
    test_val = test_val + 2;
    max = sqrt((double) test_val) + 1;
    for (i=0; i<count; i++)
    {
      if ((test_val % prime[i]) == 0) goto top;
      if (prime[i] > max) break;
    }
    count++;
    if (count == N) break;
    prime[count] = test_val;
  }
  printf("The %dth prime number is %d \n", N, test_val);
}

