How to create a random 16-digit number with the first digits?

I want to create a randomly generated 16 digit number in java. But there is a trick, I need the first two digits, which should be "52". For example, 52 89-7894-2435-1967. I was thinking of using a random generator and creating a 14-digit number and then adding the integer 5200 0000 0000 0000. I tried to find similar problems and cannot find anything useful. I am not familiar with the mathematical method, maybe this can solve the problem for me.

+4
source share
4 answers

First, you need to create a random 14-digit number, as you did:

long first14 = (long) (Math.random() * 100000000000000L);

Then you add 52at the beginning.

long number = 5200000000000000L + first14;

, , , Math.random() Random:

//Declare this before you need to use it
java.util.Random rng = new java.util.Random(); //Provide a seed if you want the same ones every time
...
//Then, when you need a number:
long first14 = (rng.nextLong() % 100000000000000L) + 5200000000000000L;
//Or, to mimic the Math.random() option
long first14 = (rng.nextDouble() * 100000000000000L) + 5200000000000000L;

, nextLong() % n , Math.random(). , , , . , .

+4
Random rand = new Random();
String yourValue = String.format((Locale)null, //don't want any thousand separators
                        "52%02d-%04d-%04d-%04d",
                        rand.nextInt(100),
                        rand.nextInt(10000),
                        rand.nextInt(10000),
                        rand.nextInt(10000));
+3

14 , "52". .

public class Tes {

    public static void main(String[] args) {
        System.out.println(generateRandom(52));
    }

    public static long generateRandom(int prefix) {
        Random rand = new Random();

        long x = (long)(rand.nextDouble()*100000000000000L);

        String s = String.valueOf(prefix) + String.format("%014d", x);
        return Long.valueOf(s);
    }
}
+2
  • 14 . Math.random
  • "52" String.
  • Convert string using method Integer.parseInt(String)
0
source

Source: https://habr.com/ru/post/1570476/


All Articles