Project Euler 6

来源:互联网 发布:看港台直播软件 编辑:程序博客网 时间:2024/06/07 06:59
'''Created on 2014年8月29日Sum square differenceThe sum of the squares of the first ten natural numbers is,12 + 22 + ... + 102 = 385The square of the sum of the first ten natural numbers is,(1 + 2 + ... + 10)2 = 552 = 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.@author: wxp2971'''# 暴力的方式直接求和计算数值sumsqr = 0num = 100for i in range(1,num+1):    sumsqr += i*isqrsum = 0for i in range(1,num+1):    sqrsum += isqrsum *= sqrsumdiff = sqrsum - sumsqrprint(diff)# 列举出几项观察后,做差只剩下交叉项×2,直接对交叉项累加求和diff = 0num = 100for i in range(1,num+1):    for j in range(i+1,num+1):        diff += 2*i*jprint(diff)# 利用数列的通项公式计算num = 100sum = (num + 1)*num/2sumsqr = (2*num + 1)*(num + 1)*num/6diff = sum*sum - sumsqrprint(int(diff))

0 0