Pergunta

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.

Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top