Best way to determine if number is triangular number?
8 ビュー (過去 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!