前n个自然数的平方和与平方和之间的差。
问题陈述
在给定数字n的情况下,编写一个程序以找到n个平方和与前n个自然数的平方之间的差。
示例
n = 3 Squares of first three numbers = 3x3 + 2x2 + 1x1 = 9 + 4 + 1 = 14 Squares of sum of first three numbers = (3 + 2 + 1)x(3 + 2 + 1) = 6x6 = 36 差异 = 36 - 14 = 22
示例
以下是用Java查找所需差异的程序。
public class JavaTester {
public static int 差异(int n){
//n个自然数的平方和
int sumSquareN = (n * (n + 1) * (2 * n + 1)) / 6;
//n个自然数的总和
int sumN = (n * (n + 1)) / 2;
//square of n个自然数的总和
int squareSumN = sumN * sumN;
//差异
return Math.abs(sumSquareN - squareSumN);
}
public static void main(String args[]){
int n = 3;
System.out.println("Number: " + n);
System.out.println("差异: " + 差异(n));
}
}输出结果
Number : 3 差异: 22
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便