k-th divisor CodeForces - 762A 题解

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值