📜  C / C++程序,用于将硬币排列成三角形时的最大高度

📅  最后修改于: 2021-05-28 04:38:45             🧑  作者: Mango

我们有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.
// C++ program to find maximum height of arranged
// coin triangle
#include 
using namespace std;
  
/* Returns the square root of n. Note that the function */
float squareRoot(float n)
{
    /* We are using n itself as initial approximation
      This can definitely be improved */
    float x = n;
    float y = 1;
  
    float e = 0.000001; /* e decides the accuracy level*/
    while (x - y > e) {
        x = (x + y) / 2;
        y = n / x;
    }
    return x;
}
  
// Method to find maximum height of arrangement of coins
int findMaximumHeight(int N)
{
    // calculating portion inside the square root
    int n = 1 + 8 * N;
    int maxH = (-1 + squareRoot(n)) / 2;
    return maxH;
}
  
// Driver code to test above method
int main()
{
    int N = 12;
    cout << findMaximumHeight(N) << endl;
    return 0;
}
输出:
4

有关更多详细信息,请参阅有关将硬币排列成三角形时的最大高度的完整文章!

想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。