I want to find the greatest integer less than or equal to the kth root of n. I tried
int(n**(1/k))
But for n=125, k=3 this gives the wrong
Here it is in Lua using Newton-Raphson method
> function nthroot (x, n) local r = 1; for i = 1, 16 do r = (((n - 1) * r) + x / (r ^ (n - 1))) / n end return r end
> return nthroot(125,3)
5
>
Python version
>>> def nthroot (x, n):
... r = 1
... for i in range(16):
... r = (((n - 1) * r) + x / (r ** (n - 1))) / n
... return r
...
>>> nthroot(125,3)
5
>>>
def nthrootofm(a,n):
a= pow(a,(1/n))
return 'rounded:{},'.format(round(a))
a=125
n=3
q=nthrootofm(a,n)
print(q)
just used a format string , maybe this helps.
Why not to try this :
125 ** (1 / float(3))
or
pow(125, 1 / float(3))
It returns 5.0, so you can use int(), to convert to int.
One solution first brackets the answer between lo and hi by repeatedly multiplying hi by 2 until n is between lo and hi, then uses binary search to compute the exact answer:
def iroot(k, n):
hi = 1
while pow(hi, k) < n:
hi *= 2
lo = hi // 2
while hi - lo > 1:
mid = (lo + hi) // 2
midToK = pow(mid, k)
if midToK < n:
lo = mid
elif n < midToK:
hi = mid
else:
return mid
if pow(hi, k) == n:
return hi
else:
return lo
A different solution uses Newton's method, which works perfectly well on integers:
def iroot(k, n):
u, s = n, n+1
while u < s:
s = u
t = (k-1) * s + n // pow(s, k-1)
u = t // k
return s
My cautious solution after being so badly burned:
def nth_root(N,k):
"""Return greatest integer x such that x**k <= N"""
x = int(N**(1/k))
while (x+1)**k <= N:
x += 1
while x**k > N:
x -= 1
return x
def nth_root(n, k):
x = n**(1./k)
y = int(x)
return y + 1 if y != x else y