1447. 最简分数
给你一个整数 n ,请你返回所有 0 到 1 之间(不包括 0 和 1)满足分母小于等于 n 的 最简 分数 。分数可以以 任意 顺序返回。
示例 1:
输入:n = 2
输出:["1/2"]
解释:"1/2" 是唯一一个分母小于等于 2 的最简分数。
1. 辗转相除法计算最大公约数
如果分子分母最大公约数非1 说明不是最简分数
说明
def gcd(top, bottom):
while top > 0:
rem = bottom % top
bottom = top
top = rem
return bottom
2. 枚举所有情况
class Solution:
def simplifiedFractions(self, n: int) -> List[str]:
def is_simple(top, bottom):
if top == 1:
return True
if bottom % top == 0:
return False
while top > 0:
rem = bottom % top
bottom = top
top = rem
return bottom == 1
res = []
for i in range(2, n+1):
for j in range(1, i):
if is_simple(j, i):
res.append(str(j) + "/" + str(i))
return res