You are given two integers n and k. Find k-th smallest divisor of n, or report that it doesn’t exist.
Divisor of n is any such natural number, that n can be divided by it without remainder.
Input
The first line contains two integers n and k (1 ≤ n ≤ 1015, 1 ≤ k ≤ 109).
Output
If n has less than k divisors, output -1.
Otherwise, output the k-th smallest divisor of n.
Example
Input
4 2
Output
2
Input
5 3
Output
-1
Input
12 5
Output
6
题目是很容易看懂的,就是让你求n从小到大的第k个因数。如果单纯的暴力,也就只需要从1扫到n,对每个数ak看(n%ak==0)成立与否,但是数据范围n最大为10^15,O(n)的复杂度也会超时,所以得优化,我们可以发现,在n是偶数的情况下最大也只能是n/2,因为n/2*2=n,所以其实观察可知,在sqrt(n)到n的数中,n的因数是很稀疏的,而且,对于每个ak>sqrt(n),必有一个ar=n/ak,因为因数是成对的,所以每个ar小于sqrt(n),都对应了一个因数ak,而且全部算起来就是全部的因数。
所以我们只需要求出小于等于sqrt(n)的所有因子就可以得到所有因子。sqrt(n)^2=n要特别判断。
#include<iostream>
#include<algorithm>
#include<string.h>
#include<string>
#include<cmath>
#include<stdio.h>
using namespace std;
long long n,k;
long long ans;
long long a[1000000];
int main(){
scanf("%lld%lld",&n,&k);
ans=-1;
long long top=0;
long long nn=sqrt(double(n));
long long i;
for(i=1;i<=nn;i++){
if(n%i==0){
a[top++]=i;
}
if(top==k){
ans=i;
break;
}
}
if(ans==-1){
bool f=0;
long long top1=top;
if(nn*nn==n)top1--;//这里不-的话会把根号n算两边。
for( i=top-1;i>=0;i--){
top1++;
if(top1==k){
f=1;
break;
}
}
if(f)ans=n/a[i];
}
printf("%lld",ans);
return 0;
}