필터 지우기
필터 지우기

Best way to determine if number is triangular number?

조회 수: 8 (최근 30일)
Richard Crozier
Richard Crozier 2012년 9월 6일
Hello,
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.
  댓글 수: 2
John D'Errico
John D'Errico 2012년 9월 6일
Note that as long as 8x+1 is no more than 2^53-1, the simple test for a perfect square will be valid. And larger than that you cannot represent x exactly anyway as a double.
Richard Crozier
Richard Crozier 2012년 9월 6일
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.

댓글을 달려면 로그인하십시오.

채택된 답변

Matt Fig
Matt Fig 2012년 9월 6일
istri = @(x) floor(sqrt(8*x+1))==sqrt(8*x+1);
x = 1:20;
idx = istri(x)
x(idx)

추가 답변 (2개)

Azzi Abdelmalek
Azzi Abdelmalek 2012년 9월 6일
편집: Azzi Abdelmalek 2012년 9월 6일
k=0
for n=1:100 %for example
x = n*(n+1)/2;
y=sqrt(8*x+1);
if round(y)==y
k=k+1;
result(k)=x
end
end
n=size(result) % you will obtain n=100, which verify the formula
or
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 2012년 9월 6일
  댓글 수: 2
Richard Crozier
Richard Crozier 2012년 9월 6일
This suggestion is fine, except that I can't actually see the solutions.
Sean de Wolski
Sean de Wolski 2012년 9월 6일
Sure you can! You just have to get addicted to it and solve a bunch of other problems first!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 NaNs에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by