![](/img/trans.png)
[英]Find number of pairs (i,j) such that i < j and A[i] >= 2A[j]
[英]For a user input n, and 1<=i<j<=n, find the number of pairs where i*i*i=j*j using python
For a user input n, and 1<=i<j<=n, find the number of pairs where i*i*i=j*j using python
程序需要從用戶那里獲取輸入,如果用戶輸入是 50,輸出應該是 3,因為有 3 個這樣的對:(1,1), (4,8), (9,27) 使用 python。
def solution(n):
count=0
for i in range(1,n):
for j in range(i,n):
if (i**3==j*j):
count+=1
return count
n=int(input())
out=solution(n)
print(out)
這是我寫的函數。 它有效,但在我正在練習的站點中,它超時並要求我進一步優化它。 我能做什么?
您可能不會計算找到匹配項的次數,而是保存索引:
def solution(n):
result = []
for i in range(1, n):
for j in range(i, n):
if i ** 3 == j ** 2:
result.append((i, j))
return result
# with list comprehension
def solution(n):
return [(i, j) for i in range(1, n) for j in range(i, n) if i ** 3 == j ** 2]
優化
通過查看值,您可以確定哪些值可以匹配,以獲得i**2 == j**3
t=you need i = x**3
和j = x**2
所以一個循環就足夠了:
def solution(n):
result = []
for i in range(1, ceil(n ** (1 / 3))):
result.append((i ** 2, i ** 3))
return result
# with list comprehension
def solution(n):
return [(i ** 2, i ** 3) for i in range(1, ceil(n ** (1 / 3)))]
作為一名程序員不應該阻止與計算機保持一分鍾的距離並思考數學問題。 由於整數可以被分解為質因數的乘積,因此 i 和 j 必須共享相同的質因數,並且對於這些質因數中的每一個,該等式都成立。 但是對於質因數,很明顯你需要有一個公數 k,其中:k 2 = i 和 k 3 = j。
所以問題可以簡化為找到所有數字 k,k >= 1 和 k 3 <= n。 如果你需要的話,i,j 對就是 k 2 , k 3
一個簡單的方法是:
def solution(n)
count = 0
for i in range(n):
if i * i * i * i * i * i <= n:
count += 1
else:
break
return count
用一個循環。
但是你可以猜測結果會接近 n 1/6 ,這將立即導致結果:
def solution(n):
def i6(i):
j = i *i * i
return j * j
i = int(n ** (1./6))
if (i == 0): return 1 # should never occur but floating point
# inaccuracy can give WEIRD results
if i6(i) > n:
return i - 1 # still floating point inaccuracy
if i6(i+1) <= n: # over convervative
return i + 1
return i
無論 n 的值是多少,只有 3 次測試,至少最多 2 48 (雙精度值的尾數大小)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.