题目

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 kth factor in this list or return -1 if n has less than k factors.

Example 1:

  1. Input: n = 12, k = 3
  2. Output: 3
  3. Explanation: Factors list is [1, 2, 3, 4, 6, 12], the 3rd factor is 3.

Example 2:

  1. Input: n = 7, k = 2
  2. Output: 7
  3. Explanation: Factors list is [1, 7], the 2nd factor is 7.

Example 3:

  1. Input: n = 4, k = 4
  2. Output: -1
  3. Explanation: Factors list is [1, 2, 4], there is only 3 factors. We should return -1.

Example 4:

  1. Input: n = 1, k = 1
  2. Output: 1
  3. Explanation: Factors list is [1], the 1st factor is 1.

Example 5:

  1. Input: n = 1000, k = 3
  2. Output: 4
  3. Explanation: Factors list is [1, 2, 4, 5, 8, 10, 20, 25, 40, 50, 100, 125, 200, 250, 500, 1000].

Constraints:

  • 1 <= k <= n <= 1000

题意

求一个正整数第k个因数。

思路

直接保存一般因数。


代码实现

Java

  1. class Solution {
  2. public int kthFactor(int n, int k) {
  3. List<Integer> factors = new ArrayList<>();
  4. boolean square = false;
  5. for (int i = 1; i * i <= n; i++) {
  6. if (n % i == 0) {
  7. factors.add(i);
  8. if (i * i == n) square = true;
  9. }
  10. }
  11. if (factors.size() * 2 - (square ? 1 : 0) < k) {
  12. return -1;
  13. }
  14. return k > factors.size() ? n / (factors.get(factors.size() * 2 - k)) : factors.get(k - 1);
  15. }
  16. }