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
Release: 2023-09-22 09:29:02
forward
600 people have browsed it

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);
}
Copy after login

Output

Enter number of coins: 13
Height of pyramid: 4
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template