-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathKth_Smallest_Factor.java
59 lines (54 loc) · 1.37 KB
/
Kth_Smallest_Factor.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import java.io.*;
import java.util.*;
class GFG {
public static void main(String args[]) throws IOException {
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(read.readLine());
while (t-- > 0) {
String S[] = read.readLine().split(" ");
int N = Integer.parseInt(S[0]);
int K = Integer.parseInt(S[1]);
Solution ob = new Solution();
System.out.println(ob.kThSmallestFactor(N, K));
}
}
}
class Solution {
static int kThSmallestFactor(int N, int K) {
int c = 0, sq = (int) Math.sqrt(N);
for (int i = 1; i <= sq; i++) {
if (N % i == 0)
c++;
if (K == c)
return i;
}
c *= 2;
if (sq * sq == N)
c--;
if (K > c)
return -1;
c = 1 + c - K;
for (int i = 1; i * i <= N; i++) {
if (N % i == 0)
c--;
if (c == 0)
return N / i;
}
return -1;
// if( K == 1 ) return 1;
// ArrayList<Integer> factors = new ArrayList<>();
// for(int i = 1; i<=Math.sqrt(N); i++ ){
// if( N % i == 0 ) factors.add(i);
// }
// int n = factors.size()-1;
// for(int i = n; i>=0; i-- ){
// if( factors.get(i) == Math.sqrt(N) ) {
// continue;
// }else{
// factors.add( N / factors.get(i) );
// }
// }
// if( factors.size() < K ) return -1;
// return factors.get(K-1);
}
};