欧拉计划第6题

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

        110的平方和为1^2+2^2+…10^2 = 385,和的平方为(1+2+…+10)^2 = 55^2 = 3025,和的平方与平方和的差为3025-385=2640

        求出1100的和的平方与平方和的差。

分析:

        思路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.

思路12程序如下:

解:

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值