✨ feat(eular_11.py):添加欧拉项目第11题的解决方案,使用NumPy计算网格中四个相邻数字的最大乘积
✨ feat(eular_12.py):添加欧拉项目第12题的解决方案,计算第一个拥有超过500个因数的三角数 📝 docs(readme.md):添加三角数的详细文档,涵盖数学概念、应用领域和博弈论中的实际例子
This commit is contained in:
72
solutions/0012.TriangularNumber/eular_12.py
Normal file
72
solutions/0012.TriangularNumber/eular_12.py
Normal file
@@ -0,0 +1,72 @@
|
||||
"""
|
||||
The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number
|
||||
would be 1+2+3+4+5+6+7=28. The first ten terms would be:
|
||||
|
||||
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
|
||||
|
||||
Let us list the factors of the first seven triangle numbers:
|
||||
|
||||
1 : 1
|
||||
3 : 1, 3
|
||||
6 : 1, 2, 3, 6
|
||||
10 : 1, 2, 5, 10
|
||||
15 : 1, 3, 5, 15
|
||||
21 : 1, 3, 7, 21
|
||||
28 : 1, 2, 4, 7, 14, 28
|
||||
|
||||
We can see that 28 is the first triangle number to have over five divisors.
|
||||
What is the value of the first triangle number to have over five hundred divisors?
|
||||
|
||||
NOTE:
|
||||
|
||||
-> in Math
|
||||
解法的核心是找到所有质因数及对应的最大幂, 根据组合数学的方法估算因数数量
|
||||
-> in Coding
|
||||
循环遍历
|
||||
"""
|
||||
|
||||
import math
|
||||
import time
|
||||
|
||||
|
||||
def timer(func):
|
||||
def wrapper(*args, **kwargs):
|
||||
start_time = time.time()
|
||||
result = func(*args, **kwargs)
|
||||
end_time = time.time()
|
||||
print(f"Time taken: {end_time - start_time} seconds")
|
||||
return result
|
||||
|
||||
return wrapper
|
||||
|
||||
|
||||
def get_factors(n):
|
||||
if n == 0:
|
||||
raise ValueError("0 没有因数集合")
|
||||
n = abs(n) # 处理负数
|
||||
factors = set()
|
||||
for i in range(1, int(math.isqrt(n)) + 1):
|
||||
if n % i == 0:
|
||||
factors.add(i)
|
||||
factors.add(n // i)
|
||||
return sorted(factors)
|
||||
|
||||
|
||||
def get_triangle_number(n: int) -> int:
|
||||
return n * (n + 1) // 2
|
||||
|
||||
|
||||
@timer
|
||||
def main_coding() -> None:
|
||||
n = 1
|
||||
while True:
|
||||
triangle_number = get_triangle_number(n)
|
||||
factors = get_factors(triangle_number)
|
||||
if len(factors) > 500:
|
||||
print(triangle_number)
|
||||
break
|
||||
n += 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main_coding()
|
||||
Reference in New Issue
Block a user