【Problem Description】
The pyramid is constructed withn layers, with each layer requiringn×n,(n−1)×(n−1),…,2×2,1×1 blocks of stone. How many blocks of stone are needed to build the pyramid in total?
【Input】
A single line containing a positive integern, representing the number of layers of the pyramid.
【Output】
A single line containing a positive integer, representing the number of blocks of stone required to build the pyramid.
【Sample Input】
2
【Sample Output】
5
【Hint】
Sample Input 2:
5
Sample Output 2:
55
【Data Range】
For all test cases, it is guaranteed that1≤n≤50.
【Problem Analysis】
This problem requires calculating the total number of stone blocks needed to build an n-layer pyramid. The construction rule is: from the bottom of the pyramid upwards, the i-th layer requires i×i blocks of stone. Therefore, the total number of blocks is equal to the sum of 1² + 2² + 3² + … + n².【Solution Approach】This is a typical problem of calculating the sum of squares. Directly using a loop to accumulate each i² (where i ranges from 1 to n) will yield the result. Since the range of n is from 1 to 50, using a loop is completely feasible and efficient enough.【Algorithm Steps Analysis】
1. Input: Read the number of layers n
2. Initialization: Set accumulator sum=0
3. Loop Accumulation: For i from 1 to n, execute sum += i×i
4. Output: Print the accumulated result sum
【Program Code Analysis】
#include <iostream> using namespace std; typedef long long ll; int main() { ll n, sum = 0; // Define the number of layers n and the accumulated sum sum, using long long to ensure large number calculations cin >> n; // Read the number of layers of the pyramid // Loop to calculate the number of stone blocks needed for each layer and accumulate for(int i = 1; i <= n; i++) { sum += i * i; // The i-th layer requires i² blocks of stone } cout << sum << endl; // Output the total number of blocks return 0; }
Code Detail Explanation:
Variable Type: Use<span><span>long long</span></span> type to store n and sum, ensuring that the calculation result does not overflow when n=50 (50²=2500, total 42925, although both are within int range, it is safer to use long long by convention).
Loop Design: Calculate the number of stone blocks needed for each layer from 1 to n and accumulate, with clear and intuitive logic.
Initialization: Initialize sum to 0 to ensure correct accumulation.
【Optimization Improvements】
Although the current code is efficient enough for n≤50, if the range of n is larger (for example, n≤10⁶), the loop method may time out, and at that point, the sum of squares formula must be used:
sum = n(n+1)(2n+1)/6
This method has a time complexity of O(1) and is highly efficient.