Problem 6:
The sum of the squares of the first ten natural numbers is, 1^2+2^2+…10^2 = 385, The square of the sum of the first ten natural numbers is, (1+2+…+10)
^2 = 55^2 = 3025, Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025-385=2640.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
问题6:
1到10的平方和为1^2+2^2+…10^2 = 385,和的平方为(1+2+…+10)^2 = 55^2 = 3025,和的平方与平方和的差为3025-385=2640。
求出1到100的和的平方与平方和的差。
分析:
思路1:按照题目给出的公式计算。
思路2:和的平方与平方和的差可以这样计算:设数字为n1~nn,则结果为:n1*n2*2+n1*n3*2+…n1*nn*2 + n2*n3*2+n2*n4*2+…n2*nn*2 + ……n(n-1)*nn*2.
思路1,2程序如下:
解:
#include <stdio.h>
typedef int INT;
typedef char CHAR;
typedef void VOID;
#define PRINT printf
INT f1(INT n) //返回[1,n]的和的平方与平方的和的差
{
if(n < 1)
return -1;
INT i;
INT nSquareOfSum, nSumOfSquare;
nSumOfSquare = 0;
for (i=1; i<=n; i++)
nSumOfSquare += i*i;
nSquareOfSum = (1 + n) * n / 2;
nSquareOfSum *= nSquareOfSum;
return nSquareOfSum - nSumOfSquare;
}
INT f2(INT n) 返回[1,n]的和的平方与平方的和的差
{
if(n < 1)
return -1;
INT i, j;
INT nRes;
nRes = 0;
for (i=1; i<=n; i++)
for (j=i+1; j<=n; j++)
nRes += i * j *2;
return nRes;
}
INT main(INT argc, CHAR *argv[])
{
INT n;
INT nRes;
while (1)
{
PRINT("请输入最大数字[1,495],输入负数退出:\n");
scanf("%d", &n);
if (n < 0)
break;
nRes = f1(n);
PRINT("f1结果:\n%d\n", nRes);
nRes = f2(n);
PRINT("f2 结果:\n%d\n\n", nRes);
}
return 0;
}