For example, the 7th triangular number is 28. How do I create something that will tell me that 28 is the 7th triangular number?
This is what I have created.
nthtri := Part[Solve[x^2 + x - (2 #) == 0, x], 2] &
This is what happens when executed.
nthtri[28]
returns
{x -> 7}
This newly defined function solves for the two roots of the quadratic equation. Since Mathematica lists the roots in increasing order, and since there are only two roots (one negative, one positive), by taking the 2nd root, you will find the "n" for a particular triangular number.
I think my current method is unprofessional and inelegant. How do I create a function that will return a singular output value? For example, I would like
nthtri[28]
to return
7
Edit: As suggested below by @Guesswhoitis, using Root
works.
nthtri := Root[x^2 + x - (2 #), 2] &
But I am still looking for more solution methods. I got lucky that solving for triangular numbers involves a quadratic equation that strictly has one positive and one negative root. If it were in a different case, for instance with a cubic formula where no such root signs are guaranteed, Root
would not be able to consistently generate correct answers.
ReplaceAll
. Alternatively, just useRoot[]
. $\endgroup$ – J. M. will be back soon♦ Jun 29 '15 at 12:32Rule
, yes? What's on the left? $\endgroup$ – J. M. will be back soon♦ Jun 29 '15 at 12:35ReplaceAll
works. $\endgroup$ – A is for Ambition Jun 29 '15 at 12:36x /. nthtri[28]
. $\endgroup$ – Eric Towers Jun 29 '15 at 17:42