feat(project):添加欧拉项目第6题解决方案及相关依赖

📝 docs(project):添加Faulhaber公式详细文档说明
⬆️ chore(project):添加numpy依赖以支持数学计算
This commit is contained in:
2025-12-15 14:55:09 +08:00
parent 65999c8456
commit be3f920e72
4 changed files with 298 additions and 1 deletions

View File

@@ -0,0 +1,43 @@
"""
The sum of the squares of the first ten natural numbers is 1^2 + 2^2 + ... + 10^2 = 385,
The square of the sum of the first ten natural numbers is (1+2+...+10)^2 = 55^2 = 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.
"""
import time
import numpy as np
def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} took {end - start:.6f} seconds")
return result
return wrapper
@timer
def sum_square_difference(n: int) -> int:
res = 0
for i in range(1, n + 1):
res += sum(np.array(list(range(1, i))) * i)
return 2 * res
@timer
def better_sum_square(n: int) -> int:
"""https://en.wikipedia.org/wiki/Faulhaber%27s_formula"""
su = ((1 + n) * n // 2) ** 2
sq = (2 * n + 1) * (n + 1) * n // 6
return su - sq
if __name__ == "__main__":
print(sum_square_difference(100))
print(better_sum_square(100))