Project Euler Homework

003.cpp

Go to the documentation of this file.
00001 
00009 #include <iostream>
00010 #include <cmath>
00011 using namespace std;
00012 
00014 unsigned ten = 1e4;
00033 class largeN
00034 {
00035   unsigned a, b, c, d;
00036   //N = a*ten^3 + b*ten^2 + c*ten + d
00037 public:unsigned sqrtN;
00038 
00039     largeN (int w, int x, int y, int z)
00040   {
00041     a = w;
00042     b = x;
00043     c = y;
00044     d = z;
00045     sqrtN = sq_root ();
00046   }
00047 
00048   unsigned remainder (unsigned k)
00049   {
00050     unsigned a1 = a % k;
00051     unsigned b1 = (a1 * ten + b) % k;
00052     unsigned c1 = (b1 * ten + c) % k;
00053     return (c1 * ten + d) % k;
00054   }
00055   largeN divide (unsigned k)
00056   {
00057     unsigned r;                 //remainder 
00058 
00059     unsigned a1 = a / k;
00060     r = a % k * ten + b;
00061     unsigned b1 = r / k;
00062     r = r % k * ten + c;
00063     unsigned c1 = r / k;
00064     r = r % k * ten + d;
00065     unsigned d1 = r / k;
00066     return largeN (a1, b1, c1, d1);
00067   }
00068   double sq_root ()             //just an estimation
00069   {
00070     if (b != 0) //division by zero if a=b=0
00071       {
00072         double factor = (1 + (double (c) * 1e4 + d) /2e8 / (double (a) * 1e4 + b));//usually equal to 1
00073         return factor * sqrt (c * ten + d);
00074       }
00075     else
00076       return sqrt (c * ten + d);
00077   }
00078   void print ()
00079   {
00080     cout << '(' << a << ',' << b << ',' << c << ',' << d << ')';
00081   }
00082 
00083 };
00084 
00085 int
00086 main ()
00087 {
00088 
00089   largeN N (0, 6008, 5147, 5143);
00090 cout << "smallest factor    upper_limit  number_N";
00091 //find smallest factor
00092   unsigned upper_limit;
00093   //loop through to find the 2nd smallest factor..., etc.
00094   do
00095     {
00096       upper_limit = N.sqrtN + 1;
00097       unsigned k;
00098       for (k = 3; k <= upper_limit; k+=2)//I bet there's no even prime factor
00099         if (N.remainder (k) == 0)//k is the smallest factor
00100           {
00101             cout << k << "    " << upper_limit << "  "; 
00102             N.print ();
00103             cout << endl;
00104             N = N.divide (k);
00105             break;
00106           }
00107       if (k > upper_limit)
00108         {
00109           cout << "*    " << upper_limit << "  ";
00110           N.print ();
00111           cout << endl;
00112           break;
00113         }
00114     }
00115   while (upper_limit >= 3);//just for safety
00116 
00117 N.print();
00118 cout << " is the largest prime factor." << endl;
00119   return 0;
00120 }
00121 
 All Classes Files Functions Variables