题目6:找出前100个自然数的“和的平方”与“平方的和”之差
题目6:找出前100个自然数的“和的平方”与“平方的和”之差Sum square difference
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.
题目翻译:
前十个自然数的平方和是:
12 + 22 + ... + 102 = 385
前十个自然数的和的平方是:
(1 + 2 + ... + 10)2 = 552 = 3025
所以平方和与和的平方的差是 3025 - 385 = 2640。
那么请找出前 100 个自然数的 “和的平方” 与 “平方的和” 之差?
视频讲解:
https://www.bilibili.com/video/BV1oN411r79B
思路解析及源码参考(C & Python):
**** Hidden Message *****
#include <bits/stdc++.h>
using namespace std;
long long res = 0;
int n;
int main() {
//scanf("%d", &n);
n = 100;
for (int i = 1; i <= n; ++i) {
res += i * (i + 1 + n) * (n - i);
}
printf("%lld\n", res);
return 0;
} #include <bits/stdc++.h>
using namespace std;
int a,b;
int main()
{
for(int i=1;i<=100;i++) a += i*i,b += i;
cout<<b*b-a<<endl;
return 0;
} print(sum(range(1, 101)) ** 2 - sum(x ** 2 for x in range(1, 101))) 这个简单 good object # 答案25164150
sum_of_squares = 0
squares_of_sum = 0
for i in range(1, 101):
sum_of_squares += pow(i, 2)
squares_of_sum += i
print(f'前100个自然数的“和的平方”与“平方的和”之差:{pow(squares_of_sum, 2) - sum_of_squares}') hdpf = sum(range(1, 101)) ** 2
pfdh = sum()
print(hdpf - pfdh)
0 1 直接模拟
Ulong test6 (Ulong n)
{
Ulong sumpo2=0;
Ulong sumpo3=0;
for(int i=1;i<=n;i++)
{
sumpo2+=i*i;
sumpo3+=i;
}
sumpo3*=sumpo3;
return sumpo3-sumpo2;
}
int main (int argc, char *argv[])
{
auto res = test6 (100);
std::cout << res << std::endl;
} 复杂度O1的数学解
Ulong test6 (Ulong n)
{
auto sumpow2=[](int n){return (n * (n + 1) * (2*n + 1)) / 6;};
auto sumpow3=[](int n){return (n*n*(n+1)*(n+1))/4;};
return sumpow3(n)-sumpow2(n);
}
int main (int argc, char *argv[])
{
auto res = test6 (100);
std::cout << res << std::endl;
}
test 看不明白,先学习下吧,
页:
[1]