## Project Euler 42: How many triangle words does the list of common English words contain?

__Problem Description__

The *n*^{th} term of the sequence of triangle numbers is given by, *t _{n}* = ½

*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 = *t*_{10}. 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?

__Analysis__

Remember Problems 44 & 45? The same logic applies except for triangle numbers. Whenever the equation ( √(1+8n) – 1 ) / 2 evaluates to an integer the number, *n*, is a triangle number.

Remember Problem 22? Well, this is the same core solution.

__Solution__

Runs < 0.01 second in Perl.

$c = 0; @h{'A' .. 'Z'} = (1 .. 26); open (IN,"<words.txt") or die "Can't open file: $!"; @words = map { /"(w+)"/ } split /,/,<IN>; foreach ( grep { is_tri(score($_)) } @words) {$c++} print "Answer to PE42 = $c"; sub is_tri {my $n=shift; my $t=(sqrt(1+8*$n)-1)/2; return int($t) == $t } sub score {my $score=0; $score+=$_ for @h{map uc, split //,shift}; return $score }; |

__Comments__

Even though we used Perl, we still kept it readable, mostly.

## Discussion

## No comments yet.