题目:
引用
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.
我的python代码:
sum_sq = 0
sq_sum = 0
for i in range(100):
sum_sq += (i + 1) ** 2
sq_sum += (i + 1)
print sq_sum ** 2 - sum_sq
看了别人写的,看来把它化简成公式更简单:
引用
(1 + 2 + ... + n)^2 = n^2 * (n+1)^2 * 1/4
1^2 + 2^2 + ... + n^2 = n * (n+1) * (2n+1) * 1/6
code:
sum_sq = 0
sq_sum = 0
n = 100
sum_sq += n * (n + 1) * (2 * n + 1) / 6
sq_sum += ((n ** 2) * (n + 1) ** 2) / 4
print sq_sum - sum_sq
分享到:
相关推荐
NULL 博文链接:https://lampeter123.iteye.com/blog/423036
ProjectEuler题1-16题代码,直接引入Eclipse就可以用
NULL 博文链接:https://lifethinker.iteye.com/blog/290159
project euler代码库1,已测试通过
NULL 博文链接:https://linuke.iteye.com/blog/1056283
Project-Euler 来自projecteuler.net的练习题 其他信息和链接:
solution to problem 5
Project Euler solutions in assembler.
欧拉计划projecteuler.net
project euler代码库第二部分(已测试通过
project euler代码库第三部分(已测试通过
project euler代码库第五部分(已测试通过
projecteuler.net 我对 Project Euler 问题的一些解决方案: :
项目欧拉解决方案该存储库包含我对 Project Euler (projecteuler.net) 上发现的编程问题的所有答案。 每个解决方案都是用 Java 编写的,旨在从命令行运行。 解决方案文件中将提供指向相关欧拉问题的链接。 某些解决...
project-euler:多种语言的projecteuler.net问题解决方案
Algorithm-hacktoberfest-projecteuler.zip,此repo包含多种语言的projecteuler问题的解决方案。为新来者特别设计,作为黑客节挑战的一部分。,算法是为计算机程序高效、彻底地完成任务而创建的一组详细的准则。
在线编程练习网站Euler project的前14题答案
ProjectEulerQuestions projecteuler.net 上问题的解决方案
project_euler Project Euler 问题的解决方案 ###Problem 1 - 3 和 5 的倍数### 如果我们列出所有 10 以下是 3 或 5 的倍数的自然数,我们得到 3、5、6 和 9。这些倍数的和是 23。求1000 以下所有 3 或 5 的倍数之...
全部在linux下运行通过并得到结果,因为是个人所做,所以不保证是最优结果,仅供交流学习 因为是个人联系所做,所以代码中没有注释,不过我相信只要你真的有去思考题目也是能知道我为什么这样做 ...