Symbol(clack:cancel)

This commit is contained in:
2025-12-26 17:35:14 +08:00
parent 266544ac47
commit 25469e1022
54 changed files with 0 additions and 0 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))