The kth Factor of n Problem
Description
LeetCode Problem 1492.
You are given two positive integers n and k. A factor of an integer n is defined as an integer i where n % i == 0.
Consider a list of all factors of n sorted in ascending order, return the k^th factor in this list or return -1 if n has less than k factors.
Example 1:
Input: n = 12, k = 3
Output: 3
Explanation: Factors list is [1, 2, 3, 4, 6, 12], the 3^rd factor is 3.
Example 2:
Input: n = 7, k = 2
Output: 7
Explanation: Factors list is [1, 7], the 2^nd factor is 7.
Example 3:
Input: n = 4, k = 4
Output: -1
Explanation: Factors list is [1, 2, 4], there is only 3 factors. We should return -1.
Constraints:
1 <= k <= n <= 1000
Follow up:
Could you solve this problem in less than O(n) complexity?
Solution
Approach: Factors Come in Pairs
The simple solution checks every i from 1 to n and counts the ones that divide n. That is O(n), which is fine for n <= 1000, but the follow-up asks for better.
Factors come in pairs: if i divides n, so does n / i, and one of the two is at most sqrt(n). So the sorted list of factors is:
- the small factors
iwithi * i <= n, in increasing order, then - the large factors
n / ifor the same smalli, which increase asidecreases.
We first walk i upward while i * i <= n, counting divisors; if we reach the k-th one, return it. Otherwise we walk the same i back down to 1 and count n / i for each divisor i.
The tricky case is a perfect square: when i * i == n, the pair is (i, i), the same factor twice. It was already counted in the first pass, so the second pass skips it. For n = 16 the factors are 1, 2, 4 (small) and then 8, 16 (large), not 4, 8, 16.
If both passes finish without reaching k, n has fewer than k factors, so we return -1.
Complexity: O(sqrt(n)) time and O(1) extra space.
class Solution:
def kthFactor(self, n: int, k: int) -> int:
# Small factors: i <= sqrt(n), in increasing order.
i = 1
while i * i <= n:
if n % i == 0:
k -= 1
if k == 0:
return i
i += 1
# Large factors: n / i for the same i, walking back down so they come out increasing.
for i in range(i - 1, 0, -1):
if n % i == 0 and i * i != n: # sqrt(n) was already counted once
k -= 1
if k == 0:
return n // i
return -1