Member-only story

Leetcode 1492: The kth Factor of n

Pierre-Marie Poitevin
1 min readJun 28, 2020

--

In this Leetcode problem, we should return the kth factor of n, or -1 if such factor doesn’t exist.

Problem statement

Solution

This is pretty much brute force:

  • Test all integers from 1 to n
  • Count the number of factors current, when current = k return the current factor value

Full code:

class Solution {
public int kthFactor(int n, int k) {
int current = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
current++;
if (current == k) {
return i;
}
}
}
return -1;
}
}

Happy coding :)

--

--

Pierre-Marie Poitevin
Pierre-Marie Poitevin

No responses yet