The kth Factor of n

You are given two positive integers n and k. A factor of n is an integer i with n % i == 0. List all factors of n in ascending order and return the kth one, or -1 if n has fewer than k factors.

30:00

The kth Factor of n
medium
Free written solution
Topics
Companies

You are given two positive integers n and k. A factor of n is an integer i with n % i == 0. List all factors of n in ascending order and return the kth one, or -1 if n has fewer than k factors.

Example 1:
Input: {"n":12,"k":3}
Output: 3
Constraints:
  • 1≤k≤n≤10001 \leq k \leq n \leq 1000

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"n":12,"k":3}

Find the 3rd smallest factor of 12. Factors come in pairs d × 12/d, so only d up to √12 ≈ 3 needs testing.

n = 12
k left = 3
√n ≈ 3
direction -

candidates d = 1 … 3

1
2
3

factor pairs d × n/d

↓ small (d)
↑ large (n/d)

no pairs found yet

factors in ascending order (want #3)

… 3 more needed

Variables
VariableValue
n12
k3
DepthFunction Call
Stack empty
0/8