Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
206 lines (202 sloc) 18.9 KB
* Solution to Project Euler problem 42
* Copyright (c) Project Nayuki. All rights reserved.
words = { (* 10 strings per line, except final line *)
* Triangle numbers are generated by t(n) = n * (n + 1) / 2.
* In reverse, given a number t, can we figure out what number n generated it?
* We solve for n using the quadratic formula and check if it's a positive integer.
* We get n = (-b + sqrt(b^2 - 4ac)) / (2a), where a = 1/2, b = 1/2, c = -t.
* Discard the minus-sqrt() solution because it is always negative.
* So we have n = (-1/2 + sqrt(1/4 + 2t)) / 2, simplified to n = (sqrt(8t + 1) - 1) / 2.
* Check that 8t+1 is square, sqrt(8t+1)-1 is even, and the result is positive.
WordValue[s_] := Total[ToCharacterCode[s] - (ToCharacterCode["A"][[1]] - 1)]
TriangleNumberQ[n_] := IntegerQ[(Sqrt[8 * n + 1] - 1) / 2]
Length[Select[words, Composition[TriangleNumberQ, WordValue]]]