Best way to determine if number is triangular number?

14 views (last 30 days)
I would like to test if an integer is a triangular number, and am wondering what the best way to achieve this is. I am aware that a triangular number is given by
x = n(n+1)/2
And that x is triangular if and only if 8x + 1 is a square.
However, what is the best way to actually test this in Matlab, giving consideration to floating point arithmetic?
I can think of methods like:
check x is an integer find if sqrt(8x + 1) is an integer to some floating point error
but there must be better ways.
Richard Crozier
Richard Crozier on 6 Sep 2012
I will only need this for relatively small numbers, it's actually a test of some user input. Useful to bear in mind though, thanks.

Sign in to comment.

Accepted Answer

Matt Fig
Matt Fig on 6 Sep 2012
istri = @(x) floor(sqrt(8*x+1))==sqrt(8*x+1);
x = 1:20;
idx = istri(x)

More Answers (2)

Azzi Abdelmalek
Azzi Abdelmalek on 6 Sep 2012
Edited: Azzi Abdelmalek on 6 Sep 2012
for n=1:100 %for example
x = n*(n+1)/2;
if round(y)==y
n=size(result) % you will obtain n=100, which verify the formula
n=1:100 %for example
x = n.*(n+1)/2;y=sqrt(8*x+1)
all(y==round(y)) % if the result is 1, the formula is checked

Sean de Wolski
Sean de Wolski on 6 Sep 2012
Sean de Wolski
Sean de Wolski on 6 Sep 2012
Sure you can! You just have to get addicted to it and solve a bunch of other problems first!

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by