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/p/3047277.html