1858 - 数数小木块

通过次数

0

提交次数

0

时间限制 : 3 秒 内存限制 : 128 MB

在墙角堆放着一堆完全相同的正方体小木块,如下图所示:

 

 因为木块堆得实在是太有规律了,你只要知道它的层数就可以计算所有木块的数量了。

现在请你写个程序 给你任一堆木块的层数,求出这堆木块的数量.


题目输入

第一行是一个整数N(N<=10)表示测试数据的组数)
接下来的n行 每行只有一个整数 ,表示这堆小木块的层数,

题目输出

对应每个输入的层数有一个输出,表示这堆小木块的总数量,每个输出占一行

输入/输出样例

输入格式

2
1
5

输出格式

1
35

C语言解答

#include<stdio.h>
int main()
{
	int N,n;
	scanf("%d",&N);
	while(N--)
	{
		int i,j,item,s;
		item=s=0;
		scanf("%d",&n);
		for(i=1;i<=n;i++)
		{
			for(j=1;j<=i;j++)
				item+=j;
		}
		s+=item;
		printf("%d\n",s);
	}
	return 0;
}

C++解答

#include "cstdio"
int main()
{
	int t,n;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d",&n);
		printf("%d\n",(n*(n+1)*(2*n+1)/6+n*(n+1)/2)/2);
	}
	return 0;
}

Java解答

import java.util.Scanner;
public class Main
{
	public static void main(String[] args)
	{
		Scanner sc=new Scanner(System.in);
		int N=sc.nextInt();
		while(N-->0)
		{
			int x=sc.nextInt();
			System.out.println((int)((Math.pow(x,3)+3*Math.pow(x,2)+2*x)/6));
		}
	}
}