Best way to determine if number is triangular number?
조회 수: 10 (최근 30일)
이전 댓글 표시
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
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.
채택된 답변
추가 답변 (2개)
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
댓글 수: 0
Sean de Wolski
2012년 9월 6일
댓글 수: 2
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 Center 및 File Exchange에서 Software Development Tools에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!