BigInt random numbers

Up a level : Algebra and Arithmetic
Previous page : RSA cryptosystem

In this page you can generate BigInt random numbers in between two given values, a, b including the given values.

It first calculates the difference c=b-a, then it splits the value c in groups of 10 digits, starting from the most significant figure. It will then loop through c in the following way:

  1. Let the result be “”.
  2. Get the most significant part not yet handled, say f.
  3. Generate a random integer between 0 and f, inclusive, say r.
  4.  If r=f, then set f to the next 10 digit part of c, else set f=10000000000. If so, use that f for all following part, except possibly the last where f=10^number of digits left.
  5. Concatenate r to the result.
  6. Repat from 3  until all parts of c is handled.
  7. Finally, add back a.

This is the code. It is a metod inside an object.

randBigBetween: function (a, b) {
    let c = b - a;
    let str = c.toString();
    let length = str.length;
    let turns = Math.floor((length - 1) / 10) + 1; // The number of parts
    // that we will loop through. It will split the string in as many
    // 10 digit part as possible + possibly one part with less than 10 digits.
    let result = '';
    let start = 0; // These two are used to index the input string.
    let end = 10;
    let extract = true; // This is set if the factors are to be extracted from
    // the string.
    let num = 0; // This will be the randomly generated integer part.
    let factor = 0; // The factor used in the random part generator.
    for (let i = 0; i < turns; i++) {
      if (extract) {
        factor = Number(str.slice(start, end)) + 1;
        num = Math.floor(Math.random() * factor);
        if (num !== factor) {
          // In this case the rest of the number
          extract = false; // can contain any digits.
          factor = 10000000000;
        }
      } else {
        num = Math.floor(Math.random() * factor);
      }
      result += num;
      start = end;
      end += 10;
      if (end > length) {
        end = length;
        factor = 10 ** (end - start);
      }
    }
    return BigInt(result) + a;
  }

 

Up a level : Algebra and Arithmetic
Previous page : RSA cryptosystemLast modified: Jul 3, 2022 @ 19:55