Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
137 views
in Technique[技术] by (71.8m points)

algorithm - find greatest number, x for given y and n such that x ^ y <= n

I need to find a greatest number, x for given y and n such that x ^ y <= n

Here n can be very large number - 1 <= n <= 10^10 and 1 <= y <= 10^5

for example : 

for y = 5 and n = 1024
x ^ 5, then x = 4 (4 ^ 5 = 1024)

for y = 5 and n = 480
x ^ 5 , then x = 3 (3 ^ 5 = 243, 4 ^ 5 = 1024) - selecting lowest one, so x = 3

i have written a small program, But i want more efficient technique because n and y can be very large.

def get(y, n):

    x = 1
    while x ** y <= n:
        x += 1
    return x - 1
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using a multiple-precision arithmetic library, such as gmpy2's iroot.

>>> import gmpy2
>>> root, exact = gmpy2.iroot(n, y)

This is simply an integer n-th root algorithm. It should be fast and correct even for huge numbers (something that floats cannot guarantee in the general case).

The second value returned is a boolean which indicates if the root is exact or not.

>>> print(*gmpy2.iroot(1024, 5))
4 True
>>> print(*gmpy2.iroot(480, 5))
3 False

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...