美文网首页
Codility 10. 1 CountFactors

Codility 10. 1 CountFactors

作者: 波洛的汽车电子世界 | 来源:发表于2019-08-23 01:18 被阅读0次

Count factors of given number n.


Task description
A positive integer D is a factor of a positive integer N if there exists an integer M such that N = D * M.

For example, 6 is a factor of 24, because M = 4 satisfies the above condition (24 = 6 * 4).

Write a function:

def solution(N)

that, given a positive integer N, returns the number of its factors.

For example, given N = 24, the function should return 8, because 24 has 8 factors, namely 1, 2, 3, 4, 6, 8, 12, 24. There are no other factors of 24.

Write an efficient algorithm for the following assumptions:

N is an integer within the range [1..2,147,483,647].

思路:
找乘子。
首先,两数相乘,其中一个乘子肯定小于\sqrt N。这是因为如果两个都大于\sqrt N,那么乘积一定大于N。
如果N = 24, 这条就保证了不会得到重复的6,4和4,6。
其次,要判断乘子的平方=N的情况。

def solution(N):
    # write your code in Python 3.6
    i = 1
    num = 0
    while(i*i<=N):
        if (N%i ==0):
            if N//i != i:
                num+=2
            else:
                num+=1
        i+=1
    return num

相关文章

网友评论

      本文标题:Codility 10. 1 CountFactors

      本文链接:https://www.haomeiwen.com/subject/efvasctx.html