Sunday 12 April 2009

PROJECT EULER #42

Link to Project Euler problem 42

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 (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, how many are triangle words?


using System;
using System.IO;

namespace ProjectEuler
{
class Program
{
static void Main()
{
//Problem 42
DateTime start = DateTime.Now;
StreamReader sr = new StreamReader(@"../../words.txt");
string s = sr.ReadToEnd().ToUpper();
string[] sa = s.Split(',');
int tWords = 0;
foreach (string s1 in sa)
{
int sum = 0;
string s2 = s1.Substring(1, s1.Length - 2);
s2.ToCharArray();
foreach (char c in s2)
{
sum += c - 64;
}
for (double j = 0; j < 25; j++)
{
tWords += j/2*(j + 1) == sum ? 1 : 0;
}
}
Console.WriteLine(tWords);
TimeSpan time = DateTime.Now-start;
Console.WriteLine("This took {0}", time);
Console.ReadKey();
}
}
}

No comments: