1

I'm currently doing some Code Wars training and am having trouble with the nth triangular test.

Here is the question:

You need to return the nth triangular number. You should return 0 for out of range values, but you will always be passed a number.

Here is my current code when n is being passed with only the values of 1, 2, and 3 (which is all that is needed to pass the test).

# Return the nth triangular number
def triangular( n )
 n * (n + 1) / 2
end

I continue to get a most of the tests passed, except I get an error:

Expected: 0; instead got: 10

If someone could kindly explain what this is even asking that would be great, can't seem to find any material online that explains this problem.

Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
Ryan Waits
  • 197
  • 1
  • 5
  • 18
  • 1
    Is `n = 4` out of range? – AGS Oct 29 '13 at 00:03
  • If a "triangular number" is as described [here](http://en.wikipedia.org/wiki/Triangular_number), your code is correct. I'm guessing the `asserts` were written just to check the required answers (i.e., for `n` = 1,2 and 3), and returned `0` for other values of `n` to avoid raising an error. – Cary Swoveland Oct 29 '13 at 00:13

1 Answers1

1

Your formula seems valid, so that must be related to the out-of-range numbers. If you got "10 instead of 0", then maybe the input data has a case of "-5" which would result in -5 * -4 / 2 = 10, but of course there should be no answer for "-5" hence expected is zero.

quetzalcoatl
  • 32,194
  • 8
  • 68
  • 107