1492. The k-th factor of n

Give you two positive integers  n and  k .

If the positive integer is  i satisfied  n % i == 0 , then we say that the positive integer  i is n a factor of the integer  .

Consider n all factors of integers  and arrange them in  ascending order  . Please return the  k first factor. If  n the number of factors is less than  k , please return  -1  .

 

Example 1:

Input: n = 12, k = 3
 Output: 3
 Explanation: The factor list includes [1, 2, 3, 4, 6, 12], and the third factor is 3.

Example 2:

Input: n = 7, k = 2
 Output: 7
 Explanation: The factor list includes [1, 7], and the second factor is 7.

Example 3:

Input: n = 4, k = 4
 Output: -1
 Explanation: The factor list includes [1, 2, 4] and there are only 3 factors, so we should return -1.

Example 4:

Input: n = 1, k = 1
 Output: 1
 Explanation: The factor list includes [1], and the first factor is 1.

Example 5:

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

 

prompt:

  • 1 <= k <= n <= 1000
package Solution1492;

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

	public static void main(String[] args) {

		Solution sol = new Solution();

		int n = 7, k = 2;
		System.out.println(sol.kthFactor(n, k));
	}

}

 

Guess you like

Origin blog.csdn.net/allway2/article/details/114828705
Recommended