//Piprime as/c't Mar09
//searches Primes in Pi 
//Pi(or other Sequences) from file "Pi.txt" 
//uses Number Theory Library (http://www.shoup.net/ntl/)
//add lib and include pathes to NTL either in Project Property 
//or in Options/Projects and Solutions/VC++ Directories
//use the same Runtime Lib i.e /MT or /MTD ... 
//here ntl.lib is renamed to ntlsse2mt.lib 

#include <iostream> 
#include <sstream>
#include <string.h>

#include <math.h> 
#include <NTL/ZZ_pX.h>

#include <NTL/lzz_pX.h>

#include <NTL/version.h>
using namespace std;

NTL_CLIENT

FILE *fpi; 

#define MAXPI 1000000
char pistr[MAXPI]; 
char pic[MAXPI];
ZZ p;

double t;
int start;
int maxindex;
int delta; 
int digits;
bool linefeeds;

int main(int argc, char *argv[]) 
{
if ((fpi=fopen ("pi.txt","r")) == NULL) 
{
	printf ("Pi.txt not found\n");
	return 1; 
}
maxindex=MAXPI;
digits=fread (pistr,1,MAXPI,fpi);
linefeeds=true;

if (digits !=MAXPI) 
{
	printf ("Digits in File %d\n",digits);
    maxindex=digits;
}
if (fpi) fclose (fpi); 

start=1;
delta=1;
             // no Parameter: start from 1, run to MAXPI with delta=1  
if (argc==2) // only 1 Parameter, just probe this size for prime and return 
{
 start=atoi (argv[1]);
 maxindex=start+1;
}

// 2 parameter: start, maxindex          : probe from  start to maxindex with delta =1      
// 3 parameter: start, maxindex, delta   : probe from  start to maxindex with delta 
// 4 parameter: -n : no linefeeds if not prime; so only primes stay on display

if (argc > 2) 
{
	start=atoi(argv[1]); 
	maxindex=atoi(argv[2]);
	cout << " start:" << start <<" to "<< maxindex << "\n";   
}
if (argc > 3) delta=atoi(argv[3]); 

if (argc > 4) linefeeds = (strcmp(argv[4],"-n")!=0);

t = GetTime();

if (start==0)  
{ 
	printf ("oops  (first parameter) has to be >0\n");
    return 1;
}

for (int i=start; i< maxindex; i+=delta) 
{
	cout <<"checking #digits=" << i<< " :"; 
  fflush(NULL); // important if with redirection,always flush buffers 
 
 strncpy (pic,pistr,i); 
 //cout <<i << ":" << pic << "\n";
 
 p=to_ZZ (pic);
 long r=ProbPrime(p, 10);
 if (r) cout <<" most likely prime\n";
 else 
 {
  cout <<" not prime";    
  if (linefeeds) cout << "\n";
  else cout << "\r";
  }
 fflush(NULL); // important if with redirection,always flush buffers 

}
t = GetTime()-t;
cout << "\n" << "time :" <<t << "s\n";
 
return 0;
}