第k个因子
Description
给你两个数 N 和 k ,请你求出 N 的因子中第k小的那个。
Input
第一行一个整数 T 表示一共有T组测试数据,接下来T行每行两个整数 N 和 k(1≤ T ≤50,1 ≤ n ≤ 10^15, 1 ≤ k ≤ 10^9)
Output
输出T行,每行一个整数,表示N的第k小的因子,如果不存在第k小因子,请输出-1
Sample Input 1
3
4 2
5 3
12 5
Sample Output 1
2
-1
6
给你两个数 N 和 k ,请你求出 N 的因子中第k小的那个。
Input
第一行一个整数 T 表示一共有T组测试数据,接下来T行每行两个整数 N 和 k(1≤ T ≤50,1 ≤ n ≤ 10^15, 1 ≤ k ≤ 10^9)
Output
输出T行,每行一个整数,表示N的第k小的因子,如果不存在第k小因子,请输出-1
Sample Input 1
3
4 2
5 3
12 5
Sample Output 1
2
-1
6
分析:这个题比较简单,就是遍历,但是由于数据量直接遍历肯定会超时,其实只要一个小小的优化就可以了
我们可以想一下,如果i是n的因子,那么n/i肯定也是n的因子了,那么我们只要判断到n的平方根就可以了,
上代码吧
import java.util.*;
public class Main {
static Scanner in = new Scanner(System.in);
static long[] f = new long[10000005];
public static void main(String[] args) {
int t = in.nextInt();
while(t-->0) {
Arrays.fill(f, 0);
int cnt = 0;
long n = in.nextLong();
int k = in.nextInt();
for(long i = 1;i*i<=n;i++) {
if(n%i==0) {
f[cnt++] = i;
if(i*i!=n)
f[cnt++] = n/i;
}
}
Arrays.sort(f,0,cnt);
if(cnt<k)
System.out.println("-1");
else
System.out.println(f[k-1]);
}
}
}
很简单,我就不说了