【每日一题0720】 除数有几个

:woman_mage:哈利波特想知道,一个正整数 n 的除数共有几个。让我们来编写一个函数告诉他吧。

示例:
divisors(4) 返回 3,因为所有除数是:1, 2, 4
divisors(5) 返回 2,因为所有除数是:1, 5
divisors(12) 返回 6,因为所有除数是:1, 2, 3, 4, 6, 12
divisors(30) 返回 8,因为所有除数是:1, 2, 3, 5, 6, 10, 15, 30

题目难度:中等
题目来源:codewars

def divisors(n): 
    pass

assert divisors(4)  == 3
assert divisors(5)  == 2
assert divisors(12) == 6
assert divisors(30) == 8

是不是有更好的解法,感觉有点不符合中等这个难度。。。

def divisors(n:int):
    num=0
    for i in range(1,n+1):
        if n%i==0:
            num=num+1
    return num
def divisors(n):
    count = 0
    for i in range(1, n + 1):
        if n % i == 0:
            count += 1
    return count


assert divisors(4) == 3
assert divisors(5) == 2
assert divisors(12) == 6
assert divisors(30) == 8
def divisors(n):
    result_num = 0
    i = 1
    while i * i < n:
        if n % i == 0:
            result_num += 2
        i += 1
    if i * i == n:
        return result_num + 1
    return result_num


assert divisors(4) == 3
assert divisors(5) == 2
assert divisors(12) == 6
assert divisors(30) == 8

:heavy_multiplication_x:到超过n就够了,算一个优化的小点吧

def divisors(n):
    """ 0720 除数有几个"""
    return len([i for i in range(1, n+1) if n % i == 0])
def divisors(n):
    return len([i for i in range(1, n+1) if n % i == 0])


assert divisors(4) == 3
assert divisors(5) == 2
assert divisors(12) == 6
assert divisors(30) == 8
def divisors(n):
    cache={1}
    cache.add(n)
    for i in range(2,n//2+1):
        if i in cache:continue
        if n%i==0:
            cache.add(i)
            cache.add(int(n/i))
    return len(cache)

assert divisors(4)  == 3
assert divisors(5)  == 2
assert divisors(12) == 6
assert divisors(30) == 8
def divisors(n):
    return sum(1 for i in range(1, n + 1) if n % i == 0)

assert divisors(4) == 3
assert divisors(5) == 2
assert divisors(12) == 6
assert divisors(30) == 8

:partying_face: :partying_face: :partying_face: :partying_face: :partying_face: :partying_face: