📜  硬币排列成三角形时的最大高度的Java程序

📅  最后修改于: 2022-05-13 01:58:09.434000             🧑  作者: Mango

硬币排列成三角形时的最大高度的Java程序

我们有 N 个硬币需要以三角形的形式排列,即第一排有 1 个硬币,第二排有 2 个硬币,以此类推,我们需要说出使用这 N 个硬币可以达到的最大高度。

例子:

Input : N = 7
Output : 3
Maximum height will be 3, putting 1, 2 and
then 3 coins. It is not possible to use 1 
coin left.

Input : N = 12
Output : 4
Maximum height will be 4, putting 1, 2, 3 and 
4 coins, it is not possible to make height as 5, 
because that will require 15 coins.
// Java program to find maximum height
// of arranged coin triangle
class GFG {
  
    /* Returns the square root of n. 
    Note that the function */
    static float squareRoot(float n)
    {
  
        /* We are using n itself as 
        initial approximation.This 
        can definitely be improved */
        float x = n;
        float y = 1;
  
        // e decides the accuracy level
        float e = 0.000001f;
        while (x - y > e) {
            x = (x + y) / 2;
            y = n / x;
        }
  
        return x;
    }
  
    // Method to find maximum height
    // of arrangement of coins
    static int findMaximumHeight(int N)
    {
  
        // calculating portion inside
        // the square root
        int n = 1 + 8 * N;
        int maxH = (int)(-1 + squareRoot(n)) / 2;
  
        return maxH;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        int N = 12;
  
        System.out.print(findMaximumHeight(N));
    }
}
  
// This code is contributed by Anant Agarwal.
输出:
4

更多详情请参考完整文章硬币排列成三角形时的最大高度!