Py3 C++利用Euclid公式達O(n)解Leetcode 1925 Count Square Sum Triples
用數論方法解畢氏定理三角整數解個數,這應該算是Diophantine Equation中最簡單的例題
------
This solution uses number theory to find the number of triangular integer solutions to the Pythagorean equation. This should be considered the simplest example in the Diophantine Equation.
class Solution:
def countTriples(self, n: int) -> int:
cnt=0
nsqrt=int(sqrt(n))
for s in range(2, nsqrt+1):
for t in range((s&1)+1, s, 2):
if gcd(s,t)!=1: continue
c=s*s+t*t
if c>n: break
k=n//c
cnt+=2*k
return cnt
沒有留言:
張貼留言