Wednesday, 9 December 2015

Kata Day 14: Triangle Number Check


Problem Description: A triangle number is a number where n objects form an equilateral triangle (it's a bit hard to explain). For example, 6 is a triangle number because you can arrange 6 objects into an equilateral triangle:

  1
 2 3
4 5 6

8 is not a triangle number because 8 objects do not form an equilateral triangle:

   1
  2 3
 4 5 6
7 8
In other words, the nth triangle number is equal to the sum of the n natural numbers from 1 to n.

Your task:

Check if a given input is a valid triangle number. Return true if it is, false if it is not (note that any 
non-integers, including non-number types, are not triangle numbers).

You are encouraged to develop an effective algorithm: test cases include really big numbers.

Assumptions:

You may assume that the given input, if it is a number, is always positive.

Notes:

0 and 1 are triangle numbers.

Level: 6kyu

Link to Kata: Triangle Number Check

So in this Kata I applied a mathematical formula looking at the patterns of triangle. For example in case of number 6, if we multiply it by 2 then the number which we obtain i.e. 12 can be expressed as a product of two consecutive numbers. Which in this case are 3 and 4. It comes down to the logic that triangle numbers are expressed as product of two consecutive numbers divided by two.

You can read more about Triangle numbers here.

So I multiplied the given number by two and then initialized a variable 'i' to 1 and checked that if any number multiplied by a number which is 1 greater than itself comes out to be equal to the given number multiplied by 2. I initialized a variable 'c' to 0 which I changed to 1 if I find any such variable satisfying the above logic.

At last I check  the value of variable 'c'. If its 1 then I output that its a triangle number else I output that the given number is not a triangle number.

Here is a link to the code: Kata Day 14

Please mention your suggestions or your doubts in the comment below.

Happy coding. :)

No comments:

Post a Comment