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

In this section, we will see one interesting problem. There are N coins, and we have to find the maximum height we can make if we arrange the coins as a pyramid. In this fashion, the first row will hold 1 coin, the second will hold 2 coins, and so on.

Coin Pyramid 1 1 1 1 1 1 Row 1: 1 coin Row 2: 2 coins Row 3: 3 coins Total coins = 1 + 2 + 3 = 6 Height = 3

In the given diagram, we can see that to make a pyramid of height three we need a minimum of 6 coins. We cannot make height 4 until we have 10 coins. The total number of coins needed for height h is the sum: 1 + 2 + 3 + ... + h = h(h+1)/2.

Syntax

int getMaxHeight(int n);

Mathematical Formula

We can get the height by solving the equation: h(h+1)/2 ? n. Using the quadratic formula, we get −

h = (-1 + ?(1 + 8n)) / 2 Where n is the number of coins h is the maximum height achievable

Example

Here is a C program to find the maximum height of a coin pyramid −

#include <stdio.h>
#include <math.h>

int getMaxHeight(int n) {
    int height = (-1 + sqrt(1 + 8 * n)) / 2;
    return height;
}

int main() {
    int N = 13;
    printf("Number of coins: %d\n", N);
    printf("Maximum height of pyramid: %d\n", getMaxHeight(N));
    
    /* Verify the calculation */
    int height = getMaxHeight(N);
    int coinsUsed = height * (height + 1) / 2;
    printf("Coins used for height %d: %d\n", height, coinsUsed);
    printf("Remaining coins: %d\n", N - coinsUsed);
    
    return 0;
}
Number of coins: 13
Maximum height of pyramid: 4
Coins used for height 4: 10
Remaining coins: 3

How It Works

  • For height h, we need h(h+1)/2 coins in total
  • We solve the inequality h(h+1)/2 ? n to find maximum h
  • The formula h = (-1 + ?(1 + 8n))/2 gives us the exact solution
  • We take the floor value since height must be an integer

Conclusion

The maximum height of a coin pyramid can be calculated using the quadratic formula derived from the triangular number sequence. This approach efficiently determines the pyramid height in O(1) time complexity.

Updated on: 2026-03-15T10:53:59+05:30

674 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements