Codility每周一课大数据,机器学习,人工智能

Codility每周一课:L10 Prime and compo

2019-01-29  本文已影响1人  AiFany
0.png
P10.1 CountFactors

Count factors of given number n.

正整数D是正整数N的一个因子,如果存在一个整数M,使得N=D*M。

例如,6是24的因子,因为M=4满足上述条件(24=6*4)。

编写函数:

def solution(N)

给定一个正整数N,则返回其因子的个数。

例如,如果N=24,函数应该返回8,因为24有8个因子,即1、2、3、4、6、8、12、24。

假定:

  1. N是区间[1,2147483647]内的整数;

不用遍历所有的小于N的数,只要遍历不小于N的平方根的数即可。因为每次遍历都可以获得2个因子。

# -*- coding:utf-8 -*-
# &Author  AnFany
# Lesson 10:Prime and composite numbers
# P 10.1 CountFactors


def solution(N):
    """
    返回N的所有因子的个数,时间复杂度O(sqrt(N))
    :param N: 正整数N
    :return: 返回N的所有因子的个数
    """
    factor_dict = {}
    for i in range(1, int(N ** 0.5) + 1):
        if N % i == 0:
            if i not in factor_dict:
                factor_dict[i] = 0
            j = N / i
            if j == int(j) and j not  in factor_dict:
                factor_dict[j] = 0
    return len(factor_dict)
image

点击获得更多编程练习题。欢迎Follow,感谢Star!!! 扫描关注微信公众号pythonfan,获取更多。

image image
上一篇下一篇

猜你喜欢

热点阅读