小编opp*_*yer的帖子

找到比数字大的 2 的幂的最快方法

我试图找到一种非常快速的方法来找到比非常大的数字 (1,000,000) 位数更高的 2 次幂。例如,我有 1009,并且想找到它的下一个更高的 2 次幂,即 1024 或 2**10

我尝试使用循环,但对于大量数据,这是非常非常慢的

y=0
while (1<<y)<1009:
   y+=1
print(1<<y)
1024
Run Code Online (Sandbox Code Playgroud)

虽然这有效,但对于大于一百万位的数字,它很慢。是否有比大数字更快的算法来找到 2 的下一个更高的幂?

由@JonClements 回答

使用 2**number.bit_length() 效果很好。所以这也适用于大数字。谢谢乔恩。

以下是 Jon 实现的代码示例:

2**j.bit_length() 
1024
Run Code Online (Sandbox Code Playgroud)

这是使用移位运算符的代码示例

2<<(j.bit_length()-1) 
1024
Run Code Online (Sandbox Code Playgroud)

这是使用百万长度数的时间差,移位运算符和 bit_length 明显更快:

len(str(aa))
1000000

def useBITLENGTHwithshiftoperator(hm):
  return 1<<hm.bit_length()-1<<1

def useBITLENGTHwithpowersoperator(hm):
  return 2**hm.bit_length()

start = time.time() 
l=useBITLENGTHwithpowersoperator(aa) 
end = time.time() 
print(end - start)                                                                                                                                 
0.014303922653198242                                                                                                                                             

start = time.time() 
l=useBITLENGTHwithshiftoperator(aa) 
end = time.time() 
print(end - start)                                                                                                                                 
0.0002968311309814453
Run Code Online (Sandbox Code Playgroud)

python math

5
推荐指数
1
解决办法
190
查看次数

如何在 pandas 或 numpy 中对横截面进行切片?

我有以下数据框,可以将其复制/粘贴并制作为数据框: df = pd.read_clipboard()

    0   1   2   3   4   5   6   7   8   9   10  11  12  13  14  15
0    0   1   5  12  13   7   1   5   5   1   7  13  12   5   1   0
1    1   0   4  13  12   6   0   4   4   0   6  12  13   4   0   1
2    5   4   0   9   8   2   4   0   0   4   2   8   9   0   4   5
3   12  13   9   0   1  11  13   9 …
Run Code Online (Sandbox Code Playgroud)

python arrays numpy slice pandas

4
推荐指数
1
解决办法
434
查看次数

Why is pow(num, power, mod) so much faster than (num ** power) % mod?

I have a question, how does

pow(num, power, mod)
Run Code Online (Sandbox Code Playgroud)

work so much faster than

(num**power)%mod
Run Code Online (Sandbox Code Playgroud)

On large numbers the second is unusable, so i'm wondering how pow() works. How does it work to be so much faster, what is the underpinning of how it works with mod to calculate an answer so much faster than

(num**power)%mod.

Run Code Online (Sandbox Code Playgroud)

(num * * power)%mod is unusable with larger numbers

so i'm wondering what trick pow() uses to calculate the answer so quickly? Does it …

python math

2
推荐指数
1
解决办法
53
查看次数

标签 统计

python ×3

math ×2

arrays ×1

numpy ×1

pandas ×1

slice ×1