The Difference Between Sum of Squares and Square of the Sum
- 时间:2020-09-10 12:55:33
- 分类:网络文摘
- 阅读:98 次
The sum of the squares of the first ten natural numbers is,
1^2+2^2+3^2+…10^2=385The square of the sum of the first ten natural numbers is,
(1+2+…+10)^2=55^2=3025Hence 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.
Bruteforce Algorithm
Given the input is 100, we can bruteforce.
1 2 3 4 5 6 7 | let sum = 0; let square_sum = 0; for (let i = 1; i <= 100; ++ i) { sum += i; square_sum += i * i; } console.log(square_sum - sum * sum); |
let sum = 0; let square_sum = 0; for (let i = 1; i <= 100; ++ i) { sum += i; square_sum += i * i; } console.log(square_sum - sum * sum);
The answer is 25164150
Math Formula to compute the Difference Between Sum of Squares and Square of the Sum
We know the Sum of first N Natural numbers is: . It would be great if we can find out the formula for the sum of squares.
Let’s assume is it (the sum of squares) . The first few values:
With these four equations, we can obtain the following values by solving the system of equations:
Thus, the f() function can be guessed as:
We just have to prove this by induction:
Both sides are equals, thus the correct formula has been obtained.
Therefore, it can be computed pretty quickly in O(1) constant time by any input value:
1 2 3 4 | const limit = 100; const sum = limit * (limit + 1) / 2; const sum_eq = (2*limit + 1) * (limit + 1) * limit / 6; console.log(sum*sum-sum_eq); |
const limit = 100; const sum = limit * (limit + 1) / 2; const sum_eq = (2*limit + 1) * (limit + 1) * limit / 6; console.log(sum*sum-sum_eq);
–EOF (The Ultimate Computing & Technology Blog) —
推荐阅读:腊肉的风味和特点及腊肉的制作全过程 腊肉的营养价值及腊肉的食用禁忌 煲汤的诀窍及胡萝卜熟吃煮汤更营养 胡萝卜不但可以保护视力还对精子有益 节令食品年糕的营养价值与食用禁忌 如何吃辣椒不上火?怎样吃辣椒更健康? 冬季养生黄金期可多吃这些保健食物 三种食物滋阴润燥蜂蜜是冬天补养佳品 川贝雪梨适合秋咳 甘草片止咳不治咳 花生营养丰富怎么吃对人体健康最有益
- 评论列表
-
- 添加评论