'Random Big Integer In Range JavaScript

I need a random integer between 0 and an integer with over 1000 decimal places.

Working with integers this large is easy with: big-integer (NPM), but there is no random method, and Math.random() doesn't express enough precision to cover the domain.

Does anyone know a clever way of generating pseudo random integers in a large range in JavaScript?



Solution 1:[1]

I think best solution for your case in Node.JS is crypto.randomBytes(size, [callback]);

Solution 2:[2]

Perhaps this:

var crypto = require('crypto');
var biformat = require('biguint-format');

// Adjust # bytes as needed
var seed = biformat(crypto.randomBytes(8), 'dec');
bigInt(seed);

Solution 3:[3]

https://www.npmjs.com/package/random-bigint

const random = require('random-bigint')

// synchronous api, generates a random number between 0 and 2**128-1
const num = random(128) // 128 bits

FYI, ** is Exponentiation

Solution 4:[4]

function genRandomNumber(byteCount, radix) {
  return BigInt('0x' + crypto.randomBytes(byteCount).toString('hex')).toString(radix)
}

// to genrate a 8 byte number in decimal format string
const randomNumber = genRandomNumber(8, 10)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 micnic
Solution 2 cyberwombat
Solution 3 Jordan Morris
Solution 4 Mike Steelson