C/C++ Program for Maximum height when coins are arranged in a triangle

We have N coins which need to arrange in form of a triangle, i.e. first row will have 1 coin, the second row will have 2 coins and so on, we need to tell maximum height which we can achieve by using these N coins.

Examples:

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.
filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find maximum height of arranged
// coin triangle
#include <bits/stdc++.h>
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;
}

chevron_right


Output:



4

Please refer complete article on Maximum height when coins are arranged in a triangle for more details!



My Personal Notes arrow_drop_up


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.