在给定数字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