Project Euler Homework

042.cpp

00001 #include <iostream>
00002 #include <fstream>
00003 using namespace std;
00004 
00005 int char_idx(char c)
00006 {
00007         return c-'A'+1;
00008 }
00009 
00010 bool is_triangle_no(unsigned x)
00011 {
00012         //solve x=n*(n+1)/2 by iteration
00013         float n=0;
00014         float n1=0;
00015         do {
00016                 n=n1;
00017                 n1 = x/(n+1)+n/2;
00018         } while (n!=n1);
00019 
00020         if (x == (unsigned)n*(n+1)/2)return 1;
00021         else return 0;
00022 }
00023 
00024 int main()
00025 {
00026         ifstream fin;
00027         fin.open("042.txt");
00028 
00029 
00030         unsigned count=0;
00031         char c;
00032         unsigned word_value=0;
00033         while (!fin.eof()) {
00034                 fin >> c;
00035 
00036                 //ignore character "
00037                 if (c=='"')continue;
00038                 //check & restart word value if encounter ,
00039                 else if (c==',') {
00040                         if(is_triangle_no(word_value))
00041                                 count++;
00042                         
00043                         word_value=0;
00044                         continue;
00045                 } else
00046                         word_value+=char_idx(c);
00047         }
00048         fin.close();
00049         
00050         cout << count << endl;
00051         return 0;
00052 }
 All Classes Files Functions Variables