-1

I'm trying to generate a random number that must have a fixed length of exactly 70 digits.

I don't know if javascript

Math.floor((Math.random()*1000000)+1);

would ever create a number less than 70 digits?

Generate a random number of fixed length using javascript

Swapnil Yeole
  • 406
  • 3
  • 12
  • 26
  • Math. random returns a value in the interval of [0, 1[, and that times 1,000,000 will get you to six digits at most ... – 04FS Jan 30 '19 at 14:20
  • 2
    You literally copy and pasted the question and just substituted "6" for "70"…?! – deceze Jan 30 '19 at 14:21
  • And due to the limited precision of floats, even if you multiplied this with a much higher factor, you will end up with a lot of zeros at the end … that is not really “random.” (Try `Math.floor((Math.random()*1000000000000000000000)+1);` a couple of times, to see what I mean.) – 04FS Jan 30 '19 at 14:21
  • 70 digits are very long. *Why* do you need to create numbers with 70 digits? (70 digit numbers are significantly larger than `Number.MAX_SAFE_INTEGER`) – FZs Jan 30 '19 at 14:23
  • you are even cloning the wording of the other question. Did you understand what is the correct answer there and how it works? You can easily adapt it to your need – Lelio Faieta Jan 30 '19 at 14:31

3 Answers3

2

let randomString = '';
for(var i=0; i<70; i++){
  randomString+=Math.floor(Math.random()*9);
}
console.log(randomString);
1

The maximum you can encode in a 64 bit number is 9,223,372,036,854,775,807 (2^63 − 1), a 19 digits number.

If you want to have a 70 digit number, you won't be able to represent it using regular numbers. You will have to use a string representation or create your own representation.

If you want to generate a random string of 70 digits, you can do it in a single line:

const random = new Array(70).fill('').map(() => Math.floor(Math.random() * 9)).join('');
console.log(random);

You can even shorten the array creation (see @ygorbunkov comment below):

const random = [...Array(70)].map(() => Math.floor(Math.random() * 9)).join('');
console.log(random);
jo_va
  • 13,504
  • 3
  • 23
  • 47
  • 2
    Well, you can do that even more ES6: `[...Array(70)].map(()=>Math.floor(Math.random()*9)).join('')` –  Jan 30 '19 at 14:50
  • Yes indeed, this is even better, I added this to my answer and referred to your comment – jo_va Jan 30 '19 at 14:54
0

This is working perfectly fine. It return string of 70 numbers

let number = (Math.random().toFixed(70) * Math.pow(10,70)).toPrecision(70).substring(0,70);
    console.log(number);
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73