Project Euler Homework
|
00001 00005 #include <iostream> 00006 #include <fstream> 00007 using namespace std; 00008 00009 typedef unsigned long long verylong; 00010 const verylong digits = 1e18; 00011 const int length = 18; 00012 const int gps = 4; 00013 class bigN 00014 { 00015 //spilt into 16 groups, each with 19 digits 00016 //smallest place unit exists in x[0] 00017 verylong x[gps]; 00018 public: 00019 bigN () 00020 { 00021 for (int k = 0; k < gps; k++) 00022 x[k] = 0; 00023 } 00024 bigN (char str[51]) 00025 { 00026 for (int k = 0, idx = 49; idx >= 0; k++, idx -= length) 00027 { 00028 x[k] = 0; 00029 for (int i = idx - length + 1; i <= idx; i++) 00030 if (i >= 0) //the last segment may be shorter than 18 digits. 00031 x[k] = x[k] * 10 + (str[i] - '0'); 00032 } 00033 } 00034 00035 void operator+= (bigN * Y) 00036 { 00037 for (int k = 0; k < gps; k++) 00038 x[k] += Y->seg (k); 00039 for (int k = 0; k < gps - 1; k++) 00040 if (x[k] > digits) 00041 { 00042 x[k + 1] += x[k] / digits; 00043 x[k] %= digits; 00044 } 00045 } 00046 verylong seg (int k) 00047 { 00048 return x[k]; 00049 } 00050 verylong last_segment () 00051 { 00052 int k = gps - 1; 00053 while (x[k] == 0) 00054 k--; 00055 00056 return x[k]; 00057 } 00058 /* 00059 void printN() 00060 { 00061 cout << '(' << x[0]; 00062 for(int k=1;k<gps;k++) 00063 cout << ','<< x[k]; 00064 cout << ')' << endl; 00065 } */ 00066 }; 00067 00068 void 00069 import (bigN ** N) 00070 { 00071 ifstream input; 00072 input.open ("013.txt"); 00073 00074 char str[51]; 00075 for (int k = 0; k < 100; k++) 00076 { 00077 input >> str; 00078 N[k] = new bigN (str); 00079 } 00080 } 00081 00097 int 00098 main () 00099 { 00100 bigN *N[100]; 00101 import (&(N[0])); 00102 00103 bigN Sum; 00104 for (int k = 0; k < 100; k++) 00105 Sum += N[k]; 00106 00107 //Sum.printN(); 00108 cout << "The sum is " << Sum.last_segment () << "..." << endl; 00109 return 0; 00110 } 00111