Project Euler Homework

027.cpp

Go to the documentation of this file.
00001 
00015 #include <iostream>
00016 using namespace std;
00017 
00018 const unsigned MAX = 1000000;
00019 class prime_table
00020 {
00021         bool x[MAX];
00022 public:
00023         prime_table();
00024         bool has(unsigned k);
00025         unsigned next(unsigned n);
00026 };
00027 
00028 prime_table::prime_table()
00029 {
00030         //assume all except 0,1 are prime
00031         x[0]=x[1]=0;
00032         for (bool* p=x+2;p-x<MAX;p++)*p=1;
00033 
00034         for (unsigned n = 2; n < MAX;n = next(n)) {
00035                 unsigned idx=n+n;
00036                 while (idx < MAX) {
00037                         x[idx]=0;
00038                         idx+=n;
00039                 }
00040         }
00041 }
00042 
00043 unsigned prime_table::next(unsigned n)
00044 {
00045         if (n>=MAX)return MAX;
00046         bool* p = x+n;
00047         do {
00048                 p++;
00049                 if (*p)return (p-x);
00050         } while (p-x < MAX);
00051         return MAX;
00052 }
00053 
00054 bool prime_table::has(unsigned k)
00055 {
00056         return x[k];
00057 }
00058 
00059 unsigned test(prime_table& prime, int a,int b)
00060 {
00061         unsigned k;
00062         for (k=0;k< MAX;k++)
00063                 if (!prime.has(k*k+a*k+b))
00064                         break;
00065         return (k==0)?0:(k-1);
00066 }
00067 
00068 int main(int argc, char **argv)
00069 {
00070         prime_table prime;
00071         unsigned max_n = 0;
00072         int A,B;
00073         for (int i=-999;i<1000;i++)
00074                 for (int j=-999;j<1000;j++) {
00075                         unsigned temp = test(prime,i,j);
00076                         if (temp > max_n) {
00077                                 max_n=temp;
00078                                 A=i;
00079                                 B=j;
00080                         }
00081                 }
00082         cout << A*B << endl;
00083         return 0;
00084 }
 All Classes Files Functions Variables