Home >Backend Development >C++ >Write a program in C/C++ to find the maximum height when coins are arranged in a triangle.

Write a program in C/C++ to find the maximum height when coins are arranged in a triangle.

WBOY
WBOYforward
2023-09-22 09:29:02603browse

In this section, we will see an interesting problem. There are N coins. We have to find out what is the maximum height we can reach if we arrange the coins in a pyramid shape. In this way, 1 coin will be placed in the first row, 2 coins in the second row, and so on.

Write a program in C/C++ to find the maximum height when coins are arranged in a triangle.

In the given diagram, we can see that to build a pyramid with a height of 3, we need at least 6 coins. We cannot build a pyramid with a height of 4 until we have 10 coins. Now let's see how to check the maximum height.

We can use the following formula to determine the height.

Write a program in C/C++ to find the maximum height when coins are arranged in a triangle.

Example

Real-time demonstration

#include<iostream>
#include<cmath>
using namespace std;
int getMaxHeight(int n) {
   int height = (-1 + sqrt(1 + 8 * n)) / 2;
   return height;
}
main() {
   int N;
   cout << "Enter number of coins: " ;
   cin >> N;
   cout << "Height of pyramid: " << getMaxHeight(N);
}

Output

Enter number of coins: 13
Height of pyramid: 4

The above is the detailed content of Write a program in C/C++ to find the maximum height when coins are arranged in a triangle.. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete