How to generate 14-digit positive number?

How to generate 14-digit positive number?
July 9th 19 at 11:20
4 answers
July 9th 19 at 11:22
Solution
If you need a long (say 100 digits), so it can be costly (for example, the 14 digit):
BigInteger b;
do{
 b = new BigInteger(48, new SecureRandom());
} while (b.toString().length()!=14);
System.out.println(b.toString());
Why so difficult? To generate 7 two-digit, and assemble into 14-digit. - nicklaus commented on July 9th 19 at 11:25
:
1) And if you need 500 digits? Then just change the 48 to a different value.
2) int allows you to generate a 19 digit (if the least significant 63 bits).
For the 14 digit enough
long l =10000000000000L +(long)(Math.random()*90000000000000L);
- darron.Wunsch commented on July 9th 19 at 11:28
Marat, your algorithm with a while loop has an unknown execution time. And this is not good. The second option - norm, Yes. - nicklaus commented on July 9th 19 at 11:31
If you generate really large values easier to take Random and fill a byte array of the necessary size and make it to a BigInteger. If the number of bits is not a multiple of 8, additionally you need to apply a mask to the first byte. - charity84 commented on July 9th 19 at 11:34
It turns out even BigInteger has a constructor like this - charity84 commented on July 9th 19 at 11:37
: so I did and used :) - darron.Wunsch commented on July 9th 19 at 11:40
: oops, think a little)) - charity84 commented on July 9th 19 at 11:43
July 9th 19 at 11:24
Solution
Now, seems right and works fast... it's faster, well, that is)
public static BigInteger generateBigInteger(int length, Random random) {
 StringBuilder builder = new StringBuilder(length);
 builder.append(random.nextInt(9) + 1);
 for (int i = 1; i < length; i++) {
builder.append(random.nextInt(10));
}
 return new BigInteger(builder.toString());
 }


Upd: the solution above in the comments better :D
July 9th 19 at 11:26
thank you. both options are good.
July 9th 19 at 11:28
Here's another option:
ThreadLocalRandom.current().nextLong(10000000000000L, 100000000000000L);

Find more questions by tags Java