前十个自然数的平方和是:
1^2 + 2^2 + … + 10^2 = 385
前十个自然数的和的平方是:
(1 + 2 + … + 10)^2 = 552 = 3025
所以平方和与和的平方的差是3025 − 385 = 2640.
找出前一百个自然数的平方和与和平方的差。
def get_square_sub(x):
""" 递归,展开行列式 """
if x < 1:
return None
square_of_sum.append(x ** 2)
square_of_sum.append(2 * x * sum(range(1, x)))
get_square_sub(x - 1)
def get_square_sub_str(x):
""" 递归,展开行列式,不计算,存储每一项的str表达式 """
if x < 1:
return None
square_of_sum.add(str(x) + ' ** 2')
square_of_sum.add('2 * ' + str(x) + ' * sum(range(1, ' + str(x) + '))')
get_square_sub_str(x - 1)
n = 100
# 直接求解
print(pow(sum(range(1, n+1)), 2) - sum(map(lambda x: pow(x, 2), range(1, n+1))))
# 计算后求解,如(a + b) ** 2 - (a ** 2 + b ** 2) = 2 * a * b
print(2 * sum(map(lambda x: sum(range(1, x)) * x, range(2, n+1))))
# 展开行列式进行求解和平方
square_of_sum = []
get_square_sub(n)
sum_of_square = [x ** 2 for x in range(1, n+1)]
print(sum(square_of_sum) - sum(sum_of_square))
# 展开行列式,不计算,用str代替
square_of_sum = set()
get_square_sub_str(n)
sum_of_square = set([str(x) + ' ** 2' for x in range(1, n+1)])
print(sum(map(eval, square_of_sum - sum_of_square)))