2015 HUAS Provincial Select Contest #2 C 题目: 题目大意:给个金字塔形。第一层1,第二层1+2,。。。。。。,第i层1+2+。。。+i,输入N,判断它最多能积累到哪一层。 解题思路:用等差数列的求和公式(1+i)*i/2求出每行的值,再用的变量将他们的值加到一起,在与N比较,看哪个数比N大,就说明N最多在I-1行。 代码:
Description
Vanya got n cubes. He decided to build a pyramid from them. Vanya wants to build the pyramid as follows: the top level of the pyramid must consist of 1 cube, the second level must consist of 1 + 2 = 3 cubes, the third level must have 1 + 2 + 3 = 6 cubes, and so on. Thus, the i-th level of the pyramid must have 1 + 2 + ... + (i - 1) + i cubes.
Vanya wants to know what is the maximum height of the pyramid that he can make using the given cubes.
Input
The first line contains integer n (1 ≤ n ≤ 104) — the number of cubes given to Vanya.
Output
Print the maximum possible height of the pyramid in the single line.
题目大意:给个金字塔形。第一层1,第二层1+2,。。。。。。,第i层1+2+。。。+i,输入N,判断它最多能积累到哪一层。
解题思路:用等差数列的求和公式(1+i)*i/2求出每行的值,再用的变量将他们的值加到一起,在与N比较,看哪个数比N大,就说明N最多在I-1行。
代码:
1 #include<iostream> 2 #include<cstdio> 3 using namespace std; 4 int main() 5 { 6 int n,d=0,sum=0; 7 while(cin>>n) 8 { 9 if(n>=1&&n<=10000) 10 { 11 int i=1; 12 while(1) 13 { 14 sum+=(1+i)*i/2; 15 if(sum>n) 16 { 17 d=i-1; 18 break; 19 } 20 i++; 21 } 22 printf("%d ",d); 23 d=0; 24 } 25 } 26 return 0; 27 } 28