/* The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we shall call the word a triangle word. Using words.txt (http://projecteuler.net/project/words.txt), a 16K text file containing nearly two-thousand common English words, how many are triangle words? */ #include <iostream> #include <fstream> #include <vector> #include <Windows.h> using namespace std; typedef unsigned long DWORD; vector<unsigned int> Tral; bool IsTriangleNumber(unsigned int N) { for (int i=1; i<Tral.size(); i++) if (Tral[i] == N) return true; return false; } int main() { DWORD sTime = GetTickCount(); for (int n=1;;n++) { unsigned int t = n*(n-1)/2; Tral.push_back(t); if (t > 26/2*12) break; } ifstream file; file.clear(); file.open("words.txt", ios::in); if (!file.is_open()) { cerr << "file can't be opened."<< '/n'; return -1; } char letter; unsigned int ch = 0; unsigned int word = 0; unsigned int counter = 0; while (!file.eof()) { file >> letter; if (letter=='"') { file >> letter; if (letter==',') { if (IsTriangleNumber(word)) counter++; ch = 0; word = 0; continue; } } ch = letter - 64; word += ch; } cout << counter << '/n'; DWORD eTime = GetTickCount(); cout << "the running time = " << eTime - sTime << " ms." << '/n'; return 0; }