最快的方法来定义一个数字是否是一个三角形的数字 [英] Fastest method to define whether a number is a triangular number
问题描述
一个三角形的数量是n个自然数从1到n的总和。什么是要找到一个给定的正整数数目是否为一个三角形的最快的一个的方法?
A triangular number is the sum of the n natural numbers from 1 to n. What is the fastest method to find whether a given positive integer number is a triangular one?
推荐答案
如果 N
是 M
日三角号码,然后 N = M *(M + 1)/ 2
。求解 M
使用二次公式:
If n
is the m
th triangular number, then n = m*(m+1)/2
. Solving for m
using the quadratic formula:
m = (sqrt(8n+1) - 1) / 2
所以 N
是三角形的,当且仅当 8N + 1
是一个完美的正方形。要快速确定一个数字是否是一个完美的广场,看到了这个问题:<一href="http://stackoverflow.com/questions/295579/fastest-way-to-determine-if-an-integers-square-root-is-an-integer">Fastest方法来确定是否一个整数的平方根是一个整数。
So n
is triangular if and only if 8n+1
is a perfect square. To quickly determine whether a number is a perfect square, see this question: Fastest way to determine if an integer’s square root is an integer.
请注意,如果8N + 1是一个完美的正方形,然后在上面公式中的分子将永远是偶数,所以没有必要检查它是否能被2整除。
Note that if 8n+1 is a perfect square, then the numerator in the above formula will always be even, so there's no need to check that it is divisible by 2.
这篇关于最快的方法来定义一个数字是否是一个三角形的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!