[Project Euler] Problem 6
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.
好吧,我们用最傻瓜的方式来做这道题
#include <iostream>
using namespace std;
int main(){
int sumOfTheSquare = 0;
int squareOfTheSum = 0;
int sum = 0;
for (int i=1;i<=100;i++){
sumOfTheSquare +=i*i;
sum += i;
}
squareOfTheSum = sum*sum;
cout << squareOfTheSum-sumOfTheSquare << endl;
return 0;
}
![](https://pic002.cnblogs.com/images/2011/221871/2011022200410351.png)
好吧,你小时候一定不厌其烦的听你的老师给你讲高斯做加法的故事了
不管是真是假,我们有高斯公式和平方和公式
更简洁的公式法是
#include <iostream>
using namespace std;
int getSumOfTheSquare(int n){
return n*(n+1)*(2*n+1)/6;
}
int getSquareOfTheSum(int n){
int sum = n*(n+1)/2;
return sum*sum;
}
int main(){
cout << getSquareOfTheSum(100)-getSumOfTheSquare(100) << endl;
return 0;
}
好吧,你也许会说,我可以直接把“和的平方”与“平方之和”的差用公式表示出来,可以一步求出结果
那就随便吧。