Tasks Details
easy
1.
CountFactors
Count factors of given number n.
Task Score
92%
Correctness
100%
Performance
83%
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:
object Solution { def solution(n: Int): Int }
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 Scala
Time spent on task 1 minutes
Notes
not defined yet
Task timeline
Code: 05:11:53 UTC,
scala,
verify,
result: Passed
object Solution {
def solution(N: Int): Int = {
if (N < 1) sys.error(s"Invalid input: $N")
@scala.annotation.tailrec
def foo(i: Int, total: Int): (Int, Int) = {
if ((i * i) >= N) (total, i)
else if (N % i == 0) foo(i + 1, total + 2)
else foo(i + 1, total)
}
val (results, x) = foo( 1, total = 0)
if (x * x == N) results + 1
else results
}
}
Analysis
Code: 05:12:08 UTC,
scala,
final,
score: 
92
object Solution {
def solution(N: Int): Int = {
if (N < 1) sys.error(s"Invalid input: $N")
@scala.annotation.tailrec
def foo(i: Int, total: Int): (Int, Int) = {
if ((i * i) >= N) (total, i)
else if (N % i == 0) foo(i + 1, total + 2)
else foo(i + 1, total)
}
val (results, x) = foo( 1, total = 0)
if (x * x == N) results + 1
else results
}
}
Analysis summary
The following issues have been detected: timeout errors.
For example, for the input 2147483647 the solution exceeded the time limit.
Analysis
Detected time complexity:
O(sqrt(N))
expand all
Correctness tests
1.
2.289 s
OK
2.
2.321 s
OK
1.
2.309 s
OK
2.
2.300 s
OK
3.
2.310 s
OK
4.
2.300 s
OK
5.
2.308 s
OK
6.
2.300 s
OK
7.
2.282 s
OK
8.
2.308 s
OK
9.
2.319 s
OK
10.
2.314 s
OK
1.
2.290 s
OK
2.
2.314 s
OK
1.
2.320 s
OK
2.
2.288 s
OK
3.
2.291 s
OK
1.
1.934 s
OK
2.
1.899 s
OK
1.
2.298 s
OK
2.
2.317 s
OK
1.
2.315 s
OK
2.
2.291 s
OK
1.
2.315 s
OK
expand all
Performance tests
1.
2.297 s
OK
2.
2.300 s
OK
1.
2.302 s
OK
2.
2.301 s
OK
3.
2.306 s
OK
1.
2.304 s
OK
2.
2.301 s
OK
3.
2.299 s
OK
1.
2.307 s
OK
2.
2.316 s
OK
1.
2.293 s
OK
2.
2.328 s
OK
3.
2.318 s
OK
extreme_maxint
N=1,000,000,000, N=MAX_INT, N=2147,395,600
N=1,000,000,000, N=MAX_INT, N=2147,395,600
✘
TIMEOUT ERROR
running time: >8.00 sec., time limit: 2.98 sec.
running time: >8.00 sec., time limit: 2.98 sec.
1.
2.322 s
OK
2.
8.000 s
TIMEOUT ERROR,
running time: >8.00 sec., time limit: 2.98 sec.
3.
2.316 s
OK