Tasks Details
easy
1.
CountFactors
Count factors of given number n.
Task Score
100%
Correctness
100%
Performance
100%
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].
Copyright 2009–2025 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
Solution
Programming language used Python
Time spent on task 1 minutes
Notes
not defined yet
Code: 14:17:02 UTC,
java,
autosave
Code: 14:17:08 UTC,
py,
verify,
result: Passed
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
# -*- 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)
Analysis
Code: 14:17:11 UTC,
py,
final,
score: 
100
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
# -*- 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)
Analysis summary
The solution obtained perfect score.
Analysis
Detected time complexity:
O(sqrt(N))
expand all
Correctness tests
1.
0.036 s
OK
2.
0.036 s
OK
1.
0.036 s
OK
2.
0.036 s
OK
3.
0.036 s
OK
4.
0.036 s
OK
5.
0.036 s
OK
6.
0.036 s
OK
7.
0.036 s
OK
8.
0.036 s
OK
9.
0.036 s
OK
10.
0.036 s
OK
1.
0.036 s
OK
2.
0.036 s
OK
1.
0.036 s
OK
2.
0.036 s
OK
3.
0.036 s
OK
1.
0.036 s
OK
2.
0.036 s
OK
1.
0.036 s
OK
2.
0.036 s
OK
1.
0.036 s
OK
2.
0.036 s
OK
1.
0.036 s
OK
expand all
Performance tests
1.
0.036 s
OK
2.
0.036 s
OK
1.
0.036 s
OK
2.
0.036 s
OK
3.
0.036 s
OK
1.
0.036 s
OK
2.
0.036 s
OK
3.
0.036 s
OK
1.
0.036 s
OK
2.
0.036 s
OK
1.
0.036 s
OK
2.
0.040 s
OK
3.
0.036 s
OK
1.
0.036 s
OK
2.
0.040 s
OK
3.
0.040 s
OK