Solving Project Euler Problem 42 – Coded Triangle Numbers

Following up from my previous post, where I attempted Solving Project Euler Problem 13 – Large Sum, I took up Problem 42 – Coded Triangle Numbers

While the original problem is a bit more complex, Hackerrank had broken it down a bit more simpler.

Note: This solution times out after the first 2 test cases out of a total of 7 test cases. So, while the solution is technically correct, it’s not the most optimal way to go about it.

Problem Statement

The nth term of a sequence of triangle numbers is given by,

tn= 0.5 n (n+1)

So the first ten triangle numbers are:


You are given an integer. If it is a triangular number tn, print the term n corresponding to this number, else print −1

Input Format

First line of input contains an integer T denoting the number of test cases. Each of the next T lines contains an integer.

Output Format

Print the answer corresponding to each test case in a new line.



Sample Input #00:


Sample Output #00:


A Rough Solution:

def find_triangle_term(number)
  flag = 0
  (1..number).each do |num|
    if number == (0.5 * num * (num + 1)).to_i
      flag = num
      flag = 0
    break if flag > 0
  (flag == 0)? -1:flag

test_cases = STDIN.readline().chomp.to_i
loop do
  triangle_number = STDIN.readline().to_i
  puts "#{find_triangle_term(triangle_number)}"
  test_cases = test_cases - 1
  break if test_cases == 0

Breakdown of the solution:

  • Read the number of test cases from STDIN as an integer
  • Loop over the test cases
  • Read the set of numbers (1 on each line, 1 for each test case)
  • Checking each input with the find_triangle_number() function and print the output
    • find_triangle_num() function:
      • Set a flag value
      • Loop from 1 to the entered number, checking if it's a triangle number or not.
        • Assign the term value to flag if it’s a triangle number
        • Assign 0 to flag if it’s not a triangle number
      • Check flag value and return -1 or the flag value as appropriate

That's it, folks! I’ll be writing more about other problems I solve as and when they happen 🙂

Note: Solution files for this and any future Project Euler problems that I solve can be found here: Github: glnarayanan/ProjectEuler