为什么random.randint(1,2 ** n-1)返回n位长整数而不仅仅是整数本身?

时间:2014-02-13 04:38:50

标签: python python-3.x

import random 
def samplegcd (n, size ): 
""" repeats the following " size " times : Choose two 
random integers , n bits long each ( between 1 to 2**n -1). 
Checks if they are relatively prime . 
Computes the frequency and the derived approximation to pi.""" 
count =0 
  for i in range (0, size ): 
    if gcd ( random.randint(1,2**n - 1) , 
       random.randint(1,2**n - 1)) ==1: 
    count += 1 # the dreaded += 
return count /size , (6* size / count )**0.5

为什么random.randint(1,2**n - 1)返回n位长整数而不仅仅是整数本身?

1 个答案:

答案 0 :(得分:2)

random.randint(1,2**n - 1)

返回1到2 ^ n-1范围内的随机整数。与python无关。这是数学问题。如果我们想要生成n位整数(整数不超过n位),那么我们应该生成1到MAX_N_BIT_VALUE范围内的数字。可以适应n位的最大值是多少?它是2 ^ n-1。

最大2位值为11(二进制)= 3(十进制)= 2 ^ 2-1。

最大3位值为111(二进制)= 7(十进制)= 2 ^ 3-1。

最大4位值是1111(二进制)= 15(十进制)= 2 ^ 4-1。