Fastest method to define whether a number is a triangular number

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

提交回复
热议问题