ProjectEuler 6

求n个数和的平和与n的平方和的差

/**
* The sum of the squares of the first ten natural numbers is,
*
* 12 + 22 + ... + 102 = 385 The square of the sum of the first ten natural
* numbers is,
*
* (1 + 2 + ... + 10)2 = 552 = 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.
*/

代码:

private static long sumSquare(int N) {
int tmp = N;
int sum = 0;
for (int i = N - 1; i > 0; i--) {
sum += tmp * i;
tmp += i;
}
return sum * 2;
}

public static void main(String[] args) {
System.out.println(sumSquare(100));
}

思想:

1、(a1+a2+...+an)2-(a12+a22+...+an2) = 2(a1*(a2+...+an)+a2*(a3+...+an)+...+an-1*an)

2、有了上面的公式该题就很好解了,为了减少乘法次数,(乘法比加法消耗要大的多),那么可以采取动态计算法,即从上面公式的最后一项往前算,那么只需要n次乘法,n-1次加法

3、官网参考答案是将n的和的平方求出来,然后再计算平方和,需要至少n+4次乘除法,n+3次加法,看来不一定所有的解法都是公式可以最优化的

转载于:https://www.cnblogs.com/lake19901126/archive/2013/04/27/3047277.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值