程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Leetcode[1447] python3 implementation of the simplest fraction (judge coprime, GCD find the maximum common divisor)

編輯:Python
# Give you an integer n , Please return to all 0 To 1 Between ( barring 0 and 1) Satisfy that the denominator is less than or equal to n Of Simplest fraction . The score can be in the form of arbitrarily Sequential return . 
# 
# 
# 
# Example 1: 
# 
# Input :n = 2
# Output :["1/2"]
# explain :"1/2" Is the only denominator less than or equal to 2 The simplest fraction of . 
# 
# Example 2: 
# 
# Input :n = 3
# Output :["1/2","1/3","2/3"]
# 
# 
# Example 3: 
# 
# Input :n = 4
# Output :["1/2","1/3","1/4","2/3","3/4"]
# explain :"2/4" It's not the simplest fraction , Because it can be reduced to "1/2" . 
# 
# Example 4: 
# 
# Input :n = 1
# Output :[]
# 
# 
# 
# 
# Tips : 
# 
# 
# 1 <= n <= 100 
# 
# Related Topics mathematics character string number theory 42 0
# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
def gcd(self, a, b):
return a if b == 0 else gcd(b, a % b)
def simplifiedFractions(self, n: int) -> List[str]:
ret = []
for i in range(2, n + 1):
for j in range(1, i):
if gcd(i, j) == 1:
ret.append("{}/{}".format(j, i))
return ret
# leetcode submit region end(Prohibit modification and deletion)

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved