Fastest method to define whether a number is a triangular number

后端 未结 8 975
失恋的感觉
失恋的感觉 2020-12-14 12:18

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?

He

8条回答
  •  悲哀的现实
    2020-12-14 12:45

    If n is the mth triangular number, then n = m*(m+1)/2. Solving for m using the quadratic formula:

    m = (sqrt(8n+1) - 1) / 2
    

    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.

    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.

提交回复
热议问题