Created With

linkProblem 42 - Coded Triangle Numbers

linkQuestion

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?

linkSolution

euler_042.py1linkimport string2link3linkdef is_triangular(x):4link    if (((8*x) + 1)**0.5) % 1 == 0:5link        return True6link    else:7link        return False8link9linkdef word_to_number(word):10link    alphabet = list(string.ascii_lowercase)11link12link    sum_of_positions = 013link    for w in word:14link        position = alphabet.index(w.lower()) + 115link        sum_of_positions += position16link17link    return sum_of_positions18link19linkwith open("p042_words.txt", 'r') as f:20link    words = f.read().replace('"', '')21link22linktriangle_count = 023linkfor w in words.split(","):24link    value = word_to_number(w)25link    if is_triangular(value):26link        triangle_count += 1

linkDiscussion

• To identify if a number is triangular or not, we make use of this function. This formula was derived from Triangular Roots and Tests. It states that an integer x is triangular if and only if 8x+1 is a square.
• We can get a number's square root by using ** 0.5 and to check if it is a whole number or not, we compare it to % 1 == 0.
Sample usage:chevron_right
1linkx = 32link(((8*3) + 1) ** 0.5) % 1 == 03link((24 + 1) ** 0.5) % 1 == 04link(25 ** 0.5) % 1 == 05link5 % 1 == 06link0 == 07link# 3 is a triangle number8link9linkx = 410link((32 + 1) ** 0.5) % 1 == 011link(33 ** 0.5) % 1 == 012link5.75 % 1 == 013link0.75 == 014link# 4 is not a triangle number
• To convert each letter to a number corresponding to its alphabetical position, we use this function.
• We open the file that contains the words that needs to be processed. It is stored in words, and the enclosing " are removed to make string parsing easier.
• To go through each word, we split words into a list.
• We then get the value of each word, and finally check if it is a triangle number or not.

linkAnswer

Show Answerchevron_right

162

Home

Project Eulerchevron_right
Essayschevron_right
Blogschevron_right

Awesome Stuff