Fastest method to define whether a number is a triangular number

后端 未结 8 958
失恋的感觉
失恋的感觉 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:43

    We just need to check if 8*(your integer to be checked)+1 is a perfect square or not!

    public Boolean isSquare(int x)
    {
        return(Math.sqrt(x)==(int)Math.sqrt(x));    // x will be a perfect square if and only if it's square root is an Integer.
    }
    
    }
    public Boolean isTriangular(int z)
    {
        return(isSquare(8*z+1));
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-14 12:45

    I don't know if this is the fastest, but here is some math that should get you in the right direction...

    S = n (n + 1) / 2
    2*S = n^2 + n
    n^2 + n - 2*S = 0
    

    You now have a quadratic equation.

    Solve for n.

    If n does not have an fractional bits, you are good to go.

    0 讨论(0)
  • 2020-12-14 12:46

    An integer x is triangular exactly if 8x + 1 is a square.

    0 讨论(0)
  • 2020-12-14 12:46

    Home work ?

    Sum of numbers from 1 to N

    1 + 2 + 3 + 4 + ... n-1 + n

    if you add the first plus last, and then the second plus the second from last, then ...

    = (1+n) + (2+n-1) + (3+n-2) + (4+n-3) + ... (n/2 + n/2+1)

    = (n=1) + (n+1) + (n+1) + ... (n+1); .... n/2 times

    = n(n+1)/2

    This should get you started ...

    0 讨论(0)
  • 2020-12-14 12:48
       int tri=(8*number)+1;// you can remove this for checking the perfect square and remaining all same for finding perfect square
       double trinum=Math.sqrt(tri);
    int triround=(int) Math.ceil(trinum);
    if((triround*triround)==tri)
         {
         System.out.println("Triangular");
         }
        else
        {
        System.out.println("Not Triangular");
        }
    

    Here ceil will always look at next highest number so this will give a perfect chance for verification.

    0 讨论(0)
提交回复
热议问题