34

How can I generate a big (more than 64 bits) random integer in Python?

Charles Brunet
  • 21,797
  • 24
  • 83
  • 124

2 Answers2

69

You can use random.getrandbits():

>>> random.getrandbits(128)
117169677822943856980673695456521126221L

As stated in the linked documentation, random.randrange() will also do the trick if random.getrandbits() is available.

dga
  • 21,757
  • 3
  • 44
  • 51
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
1

You can also use this function to generate a number of any length.

def generateRandomNumber(digits):
    finalNumber = ""
    for i in range(digits // 16):
        finalNumber = finalNumber + str(math.floor(random.random() * 10000000000000000))
    finalNumber = finalNumber + str(math.floor(random.random() * (10 ** (digits % 16))))
    return int(finalNumber)
OhhhThatVarun
  • 3,981
  • 2
  • 26
  • 49
  • Something smells strange here. What's going on with the hard-coded values (16 and 10**16)? Isn't this going to affect the distribution of the random numbers? – Harry Jun 09 '21 at 12:28
  • @Harry not really, I'm multiplying 10**16 to the `random digit` just to remove the decimal digit. as random.random() going to output a random digit of 16 digits with a decimal. – OhhhThatVarun Jun 09 '21 at 14:29