#include <iostream.h>
#include <conio.h>
#include <fstream.h>
#include <math.h>
#include <stdio.h>
#include <time.h>

int main() {
	long prime, num, i, lastprime, n, largecount;
	double divlimit;
	ofstream f;
	clock_t start, finish, firstclock, lastclock;
	double duration, programtime;
	double space, largestspace;

	f.open("primes.txt");
	f<<"prime\tgap\tcpu\tlargest gap\tcount since last largest gap"<<endl;
	n=1;
	start = duration = lastprime = largestspace = space = 0;
	firstclock = clock();				// set program start time
	while (!kbhit()) {

		n += 2;							// start checking numbers at 3, check only odd numbers
		prime=1;
		divlimit = ceil( sqrt(n) );		// get the highest number you want to divide by

		for (i=2;i<=divlimit;i++) {
			num = n%i;					// see if the number divided evenly
			if (num == 0) {				// if any number divides evenly, its not prime
				prime=0;				// so mark it as not prime
			}
		}
		if (prime == 1) {				// print out all that weren't marked
			finish = clock();			// end the clock for this calculation
			duration = (double)(finish - start);///CLOCKS_PER_SEC; //find the time since the last prime
			space = (double)(n-lastprime);	// compute the space between this and the last prime
			if (space > largestspace) {		// see if this is the largest space so far
				largestspace = space;
				largecount=0;				// reset new largespace count
			}
			largecount++;					// increment largest space count
			cout<<n<<"\t"<<space<<"\t"<<duration<<"\t"<<largestspace<<"\t"<<largecount<<endl;
			f<<n<<"\t"<<space<<"\t"<<duration<<"\t"<<largestspace<<"\t"<<largecount<<endl;
			start = clock();				// start the clock for the next calculation
			lastprime = n;
		}
	}

	lastclock = clock();					// get program calculation finish time

	programtime = (lastclock - firstclock)/CLOCKS_PER_SEC;;

	cout<<"Largest prime: "<<lastprime<<endl;
	f<<"Largest prime: "<<lastprime<<endl;
	cout<<"Total program running time: "<<programtime<<" seconds"<<endl;
	f<<"Total program running time: "<<programtime<<" seconds"<<endl;
	cout<<"Largest gap between primes: "<<largestspace<<endl;
	f<<"Largest gap between primes: "<<largestspace<<endl;

	cin>>n;

	f.close();

	return 0;
} // end main
