我使用了强力方法并试图尽可能提高效率,但我只能在1小时后达到680的周长。我需要达到1000。
这是我试图解决的问题:
如果p是具有整数长度的直角三角形的周长>对于p = 120,恰好有三个解。{/,b}
{20,48,52},{24,45,51},{30,40,50}
对于p≤1000的值,最大化解的数量是多少?
https://projecteuler.net/problem=39
在我的解决方案中,我为每一行添加了评论,以解释它的作用。
我使用过Python 3。
import math
# Initialisation of variables:
max = 0
ans = 0
# 'i' represents the perimeter. 'c' represents the hypotenuse length. 'a' and 'b' are both sides lengths:
# This outer loop iterates through all the perimeters from 1 to 1000.
for i in range(1, 1001):
# Resets the count and arrA values.
count = 0
arrA = []
# This loop iterates through all the hypotenuse values and makes sure its less than half of the perimeter:
for c in range(1, i // 2):
# This loop iterates through all the b values where b is lesser than (perimeter - hypotenuse):
for b in range(1, i - c):
# This loop iterates through all the a values where 'a' is lesser than (perimeter - hypotenuse - other side + 1):
for a in range(1, i - c - b + 1):
# Makes sure that all sides add up to the perimeter and that hypotenuse is lesser than the sum of the 2 other sides.
if a + b + c != i or a + b <= c:
continue
# Makes sure no instances are being repeated by and b being switched:
if b in arrA:
break
# Checks if its a right angled triangle:
if math.sqrt(math.pow(a, 2) + math.pow(b, 2)) == c:
#Adds to the number of matches for the current perimeter.
count += 1
# Adds a to arrA so b can check later:
arrA.append(a)
# Extra output line for testing purposes (not needed):
print([f'{a:4}', f'{b:4}', f'{c:4}', f'{i:4}', f'{count:4}'])
# checks if the current count was a new maximum or equal to previous maximum:
if count >= max:
max = count
ans = i
#Prints final output:
print(f'Final Answer: {ans}')
以下是与上述完全相同的代码,但没有注释以便于阅读:
import math
max = 0
ans = 0
for i in range(1, 1001):
count = 0
arrA = []
for c in range(1, i // 2):
for b in range(1, i - c):
for a in range(1, i - c - b + 1):
if a + b + c != i or a + b <= c:
continue
if b in arrA:
break
if math.sqrt(math.pow(a, 2) + math.pow(b, 2)) == c:
count += 1
arrA.append(a)
print([f'{a:4}', f'{b:4}', f'{c:4}', f'{i:4}', f'{count:4}'])
if count >= max:
max = count
ans = i
print(f'Final Answer: {ans}')
即使在2小时内也没有完成,但它的周长达到了800,所以我知道它工作正常,速度非常慢。
任何帮助都将不胜感激。