1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
|
#include<iostream>
#include<fstream>
#include<string>
using std::ifstream;
using namespace std;
inline int extract_digit(istream& is)
{
int num = -1;
char ch = is.get();
if (isdigit(ch))
{
num = static_cast<int>(ch-'0');
return num;
}
}
int main()
{
string filename;
ifstream indata;
time_t begin, end;
//a-e are the current values from the file;a1-e1 are the current set that
//gives the largest product
int a, b, c, d, e, a1, b1, c1, d1, e1, largestproduct;
//cout<<"Please enter the name of the file that you'd like to use."<<endl;
//cin>>filename;
//cout<<endl;
begin=clock();
indata.open("1000digits.txt");
if (!indata)
{
cerr<<"Error: file name could not be opened."<<endl;
}
if (!indata.eof())
{
//gets the first five digits, multiplies them, and assigns that value to
//largestproduct
a=extract_digit(indata);
b=extract_digit(indata);
c=extract_digit(indata);
d=extract_digit(indata);
e=extract_digit(indata);
largestproduct=a*b*c*d*e;
a1=a; b1=b; c1=c; d1=d; e1=e;
}
while (!indata.eof())
{
//moves the values of b, c, d, and e to the next variable down and
//assigns the next number from the file to e
a=b; b=c; c=d; d=e; e=extract_digit(indata);
//if any variables are 0, the product of the sequence is 0 and not
//what we're looking for; skip this iteration
if(a*b*c*d*e==0)
continue;
//if the program identifies a new largestproduct, it stores the product
//and the variables used to achieve it.
if (largestproduct<(a*b*c*d*e))
{
largestproduct=a*b*c*d*e;
a1=a; b1=b; c1=c; d1=d; e1=e;
}
}
cout<<"The five consecutive digits from your file that produce the largest";
cout<<" product are: "<<a1<<", "<<b1<<", "<<c1<<", "<<d1;
cout<<", and "<<e1<<"."<<endl;
cout<<"The product of those digits is ";
cout<<largestproduct<<"."<<endl;
double diff=(double)(end-begin)/(double)CLOCKS_PER_SEC;
cout<<"Elapsed calculation time: "<<diff<<endl;
cin.sync();
cin.get();
return(0);
}
|