C/C++ Program for Number of solutions to Modular Equations?

We have a given number of coins and we need to arrange them to form a pyramid of maximum height. The coins are arranged such that the first row contains 1 coin, the second row contains 2 coins, the third row contains 3 coins, and so on.

1 2 3 4 5 6 Row 1: 1 coin Row 2: 2 coins Row 3: 3 coins Total coins used: 6, Height: 3

In the diagram above, we create a pyramid using 6 coins with a height of 3. To make a pyramid of height 4, we would need 10 coins (1+2+3+4). The maximum height can be calculated using the quadratic formula derived from the sum of first n natural numbers.

Syntax

H = (-1 + ?(1 + 8*N)) / 2

Where N is the number of coins and H is the maximum height of the pyramid.

Example

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

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

int main() {
    int n = 10;
    int height = (-1 + sqrt(1 + 8 * n)) / 2;
    printf("Number of coins: %d\n", n);
    printf("Height of pyramid: %d\n", height);
    
    /* Verify the calculation */
    int total_coins_used = (height * (height + 1)) / 2;
    printf("Coins used for height %d: %d\n", height, total_coins_used);
    
    return 0;
}
Number of coins: 10
Height of pyramid: 4
Coins used for height 4: 10

How It Works

The formula is derived from the sum of first n natural numbers: 1 + 2 + 3 + ... + h = h(h+1)/2. Setting this equal to N and solving the quadratic equation h² + h - 2N = 0 gives us the formula for maximum height.

Conclusion

The coin pyramid problem demonstrates how mathematical formulas can efficiently solve geometric arrangement problems. Using the quadratic formula, we can directly calculate the maximum height without iterative approaches.

Updated on: 2026-03-15T11:31:49+05:30

190 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements