
//  This program generates a list of all the 
//  prime numbers
//  in the range from 1 to 10000000


#include <math.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>


#define MAX 10000000

unsigned long i,j,sum,lower,upper;

int number[MAX];

FILE *pFile[1];
char filename[1][15];

void main()
{

	printf("\n prime.cpp  version 1.2 \n");
	printf("\n By Tom Irvine   Email:  tomirvine@aol.com \n");

	printf("\n This program generates a list of all the prime numbers");
	printf("\n in a range defined by the user. \n");


    long(ia);

    printf("\n Enter the lower limit \n");
    scanf("%ld",&ia);
	
    printf("\n\n Enter the upper limit \n");
	scanf("%ld",&upper);

	if(upper > (MAX-1))
	{
        printf("\n Maximum upper limit = MAX \n");

		upper = (MAX-1);
	}

    if(ia < 1 ){ia =1;}
	if(ia > upper)
	{ 
		printf("\n Input error. \n");
	    exit(1);
	}

	lower = unsigned long(ia);


	printf("\n Calculating....");



//  The output file is prime.out

    strcpy(filename[0],"prime.out");
	pFile[0]=fopen(filename[0],"w");

//  The number array is initialized to zero.  
//  A zero will mean that the number is prime.
//  A one will indicate that the number is 
//  non-prime.

    for(i=0; i< MAX; i++)
	{
		number[i]=0;
	}

	for(i=2; i<= 1+unsigned long(upper/2); i++)
	{
	   sum = i;

	   if(number[sum]==0)
       {
	      for(j=0; j<= 1+unsigned long(upper/2); j++)
		  {
		     sum+=i;
		     if( sum >= (upper+1) ){break;}

// The number array is given a value of 1 
// for non-prime numbers.

		     number[sum]=1;
		  }
       }
	}

	fprintf(pFile[0],"\n Prime numbers \n");

    if(lower < 2){lower = 2;}

    for(i=lower; i<=upper; i++)
	{

// The number array has a zero value if the number
// is prime
		
		if( number[i] == 0 )
		{
		   fprintf(pFile[0],"%ld\n",i);
		}
	}


	printf("\n\n The output file is prime.out \n");

	printf("\n\n Calculation complete. \n\n Press any key to exit.");
	getch();
}
