前 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 Difference = 36 - 14 = 22
举例说明
以下是用 Java 编写的程序,用于查找所需的差值。
public class JavaTester {
public static int difference(int n){
//sum of squares of n natural numbers
int sumSquareN = (n * (n + 1) * (2 * n + 1)) / 6;
//sum of n natural numbers
int sumN = (n * (n + 1)) / 2;
//square of sum of n natural numbers
int squareSumN = sumN * sumN;
//difference
return Math.abs(sumSquareN - squareSumN);
}
public static void main(String args[]){
int n = 3;
System.out.println("Number: " + n);
System.out.println("Difference: " + difference(n));
}
}输出
Number : 3 Difference: 22
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP