It turns out that 12 cm is the smallest length of wire that can be bent to form an integer sided right angle triangle in exactly one way, but there are many more examples.
12 cm: (3,4,5)
24 cm: (6,8,10)
30 cm: (5,12,13)
36 cm: (9,12,15)
40 cm: (8,15,17)
48 cm: (12,16,20)
In contrast, some lengths of wire, like 20 cm, cannot be bent to form an integer sided right angle triangle, and other lengths allow more than one solution to be found; for example, using 120 cm it is possible to form exactly three different integer sided right angle triangles.
120 cm: (30,40,50), (20,48,52), (24,45,51)
Given that L is the length of the wire, for how many values of L ≤ 1,500,000 can exactly one integer sided right angle triangle be formed?
以下是出自wikipedia
Euclid's formula[1] is a fundamental formula for generating Pythagorean triples given an arbitrary pair of positive integers m and n with m > n. The formula states that the integers
form a Pythagorean triple. The triple generated by Euclid's formula is primitive if and only if m and n are coprime and m − n is odd. If both m and n are odd, then a, b, and c will be even, and so the triple will not be primitive; however, dividing a, b, and c by 2 will yield a primitive triple if m and n are coprime.[2]
Every primitive triple arises from a unique pair of coprime numbers m, n, one of which is even. It follows that there are infinitely many primitive Pythagorean triples. This relationship of a,b and c to m and n from Euclid's formula is referenced throughout the rest of this article.
Despite generating all primitive triples, Euclid's formula does not produce all triples—for example, (9, 12, 15) cannot be generated using integer m and n. This can be remedied by inserting an additional parameter k to the formula. The following will generate all Pythagorean triples uniquely:
where m, n, and k are positive integers with m > n, m − n odd, and with m and n coprime.
That these formulas generate Pythagorean triples can be verified by expanding a2 + b2 using elementary algebra and verifying that the result coincides with c2. Since every Pythagorean triple can be divided through by some integer k to obtain a primitive triple, every triple can be generated uniquely by using the formula with m and n to generate its primitive counterpart and then multiplying through by k as in the last equation.
Many formulas for generating triples with particular properties have been developed since the time of Euclid.
import math
L = 1500000
maxm = int(math.sqrt(L/2))
triple = [0 for x in range(0,L+1)]
ans = 0
def gcd(m,n):
if m < n:
tmp = m
m = n
n = tmp
while n:
m = m - n
if m < n:
tmp = m
m = n
n = tmp
return m
for m in range(2,maxm):
for n in range (1,m):
if ((m+n)%2)==1 and gcd(m,n)==1:
a=m*m-n*n
b=2*m*n
c=m*m+n*n
p=a+b+c
while p<=L:
triple[p]=triple[p]+1
if triple[p]==1:
ans=ans+1
if triple[p]==2:
ans=ans-1
p=p+a+b+c
print('ans = ',ans)