Project Euler Homework

030.cpp

Go to the documentation of this file.
00001 
00012 #include <iostream>
00013 #include <algorithm>
00014 using namespace std;
00015 
00016 const int MAX = 7;
00020 class digits
00021 {
00022   unsigned short x[MAX];
00023 public:
00024     digits ();
00026   void next ();
00027   bool end ();
00029   unsigned f ();
00030   bool operator== (unsigned fx);
00031 };
00032 digits::digits ()
00033 {
00034   x[0] = x[1] = 1;
00035   for (int i = 2; i < MAX; i++)
00036     x[i] = 0;
00037 }
00038 
00039 
00040 unsigned
00041 digits::f ()
00042 {
00043   unsigned sum_of_powers = 0;
00044   for (int i = 0; i < MAX; i++)
00045     {
00046       unsigned short d = x[i];
00047       sum_of_powers += d * d * d * d * d;
00048     }
00049   return sum_of_powers;
00050 }
00051 
00052 void
00053 digits::next ()
00054 {
00055   int i = 0;
00056   while (x[i] == 9 && i < MAX)
00057     i++;
00058   if (i == MAX)                 //overflow
00059     {
00060       x[MAX - 1] = 10;
00061       return;
00062     }
00063   else
00064     {
00065       x[i]++;
00066       while (i > 0)
00067         {
00068           x[i - 1] = x[i];
00069           i--;
00070         }
00071     }
00072 }
00073 
00074 bool
00075 digits::end ()
00076 {
00077   return (x[MAX - 1] == 10);
00078 }
00079 
00080 bool
00081 digits::operator== (unsigned fx)
00082 {
00083   unsigned short y[MAX];
00084   copy (x, x + MAX, y);
00085   for (; fx > 0; fx /= 10)
00086     {
00087       unsigned short d = fx % 10;
00088       if (d == 0)
00089         continue;
00090       unsigned short *p = find (y, y + MAX, d);
00091       if (p == y + MAX)
00092         return 0;               //return false
00093       else
00094         *p = 0;
00095     }
00096 
00097   for (int i = 0; i < MAX; i++)
00098     if (y[i] != 0)
00099       return 0;                 //check if list is empty
00100 
00101   return 1;
00102 }
00103 
00108 int
00109 main ()
00110 {
00111   unsigned sum = 0;
00112   for (digits X; !X.end (); X.next ())
00113     {
00114       unsigned fx = X.f ();
00115       if (X == fx)
00116         sum += fx;
00117     }
00118   cout << sum << endl;
00119   return 0;
00120 }
00121 
 All Classes Files Functions Variables