zl程序教程

您现在的位置是:首页 >  后端

当前栏目

【Leetcode刷题Python】改进的算法,高效求一个数的因子

PythonLeetCode算法 一个 高效 刷题 改进 因子
2023-09-14 09:13:00 时间

1 思路

不用全部遍历,只遍历1到根号(n)的范围即可。
当i是可以整除的,用n/i得到的是相对另一个因子。
时间复杂度 O ( n 1 / 2 ) O(n^{1/2}) O(n1/2)

2 实现

import math
def low_fac(n):
    ans = []
    for i in range(1,int(math.sqrt(n))):
        
        if n%i==0:
            if i*i>n:
                ans.append(i)
            t = int(n/i)
            if t!=i and t*t>n:
                ans.append(t)
    return ans