题解 | 幂次进近

幂次进近

https://www.nowcoder.com/practice/1eda6676a6e544838263d8de9a8f3eed

本题数比较大,所以可以用py解决,但是py也需要特判三个点,不然会超时

k=1时直接输出n

k>60直接输出1,因为 (2**61 > 1e18),大于 60 的 k,整数根可能只有 1

n=1直接输出1

代码如下:

def fastpow(a,b):
    ans=1
    while b!=0:
        if b&1:
            ans*=a
        b>>=1
        a*=a
    return ans
t=int(input())
for _ in range(t):
    n,k=map(int,input().split())
    if k==1:
        print(n)
        continue
    if n==1 or k>60:
        print(1)
        continue
    l=0
    r=10**18
    while l+1<r:
        mid=(l+r)//2
        if fastpow(mid,k)<=n:
            l=mid
        else:
            r=mid
    res1=abs(n-fastpow(l,k))
    res2=abs(n-fastpow(l+1,k))
    if res1>res2:
        print(l+1)
    else:
        print(l)

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务