[英]Write a function that, given natural numbers n, m, determines the smallest natural number k such that n^k >= m, in time O(log k)
I can do it in only O(k) time can someone be that kind to help me.我只能在 O(k) 时间内完成,有人可以帮助我吗? I can not use build in functions.我不能使用内置函数。
def potnr(a, b):
rez = 1
while b>0:
if b%2:
rez = rez * a
b = b // 2
a = a * a
return rez
def liczba(n, m):
k = 1
while potnr(n, k) < m:
k += 1
return k
print(liczba(2, 16))
I can do it in only O(k) time can someone be that kind to help me我只能在 O(k) 时间内完成,有人可以帮助我吗
n^k >= m
if and only if k >= log m base n
n^k >= m
当且仅当k >= log m base n
Since log m base n = log m / log n
, this is as simple as:由于log m base n = log m / log n
,这很简单:
from math import log, ceil
def smallest_k(n, m):
return ceil(log(m)/log(n))
This runs in O(1)
time.这在O(1)
时间内运行。
This one should work (I just fixed the value of k returned, for there was no guarantee it was the smallest value with the previous return):这个应该可以工作(我只是修复了返回的 k 值,因为不能保证它是前一个返回值的最小值):
import math
def min_power(n,m):
b=1
while n**b < m:
b *= 2
a = b/2
while b-a > 1:
c = (a+b)/2
if n**c < m:
a = c
else:
b = c
k = math.ceil(a)
return k if (n**k >= m) else k+1
min_power(35,10**250)
# Out[23]: 162
First determine any natural number k
for which n ^ k >= m
.首先确定n ^ k >= m
的任何自然数k
。 Then refine your estimate to find the smallest such k
.然后细化您的估计以找到最小的这样的k
。
It's easiest to find the initial estimate for k
as a power of 2. Have a temporary value which holds n ^ k
.最简单的方法是找到k
的 2 次幂的初始估计值。有一个包含n ^ k
的临时值。 Start from k = 1
, repeatedly multiply k
by 2, and square your temporary variable, until your k
is sufficiently big.从k = 1
开始,重复将k
乘以 2,并对临时变量求平方,直到您的k
足够大。
Your real k
will be greater than half the estimate you found.您的实际k
将大于您找到的估计值的一半。 Numbers in that range have log2(k)
bits.该范围内的数字有log2(k)
位。 Check each bit, starting from the most significant one.检查每一位,从最重要的一位开始。 For each such bit, calculate n ^ k
for two values of k
: with that bit equal to 0 and 1. Compare with m
- this will tell you the value of that bit.对于每个这样的位,为 k 的两个值计算n ^ k
k
该位等于 0 和 1。与m
比较 - 这将告诉您该位的值。 Proceed to lower-significant bits, until you get to bit 0 (least significant bit).继续处理较低有效位,直到到达位 0(最低有效位)。
I am not sure you are allowed to assume that calculating n ^ k
has O(1) complexity.我不确定您是否可以假设计算n ^ k
的复杂度为 O(1)。 If not, you have to store intermediate results for all n ^ k
calculations at first stage, or alternatively, use sqrt
to calculate lesser powers of n
.如果不是,您必须在第一阶段存储所有n ^ k
计算的中间结果,或者使用sqrt
来计算n
的次幂。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.