Reputation: 109
I'm trying to find a way to generate a very big random number. I looked online but couldn't find what I was looking for. I need to generate a random number that is between 1111111111111111111111 and 9999999999999999999999; the number is 22 digits long. If you know how to do it then plz let me know. Thanks
Upvotes: 0
Views: 370
Reputation: 627
Here is quick TESTED solution for your needs :
public void generateNumber(){
BigInteger min = new BigInteger("1111111111111111111111");
BigInteger max = new BigInteger("9999999999999999999999");
System.out.println(random(min, max));
}
protected static Random RANDOM = new Random();
public static BigInteger random(BigInteger min, BigInteger max) {
if(max.compareTo(min) < 0) {
BigInteger tmp = min;
min = max;
max = tmp;
} else if (max.compareTo(min) == 0) {
return min;
}
max = max.add(BigInteger.ONE);
BigInteger range = max.subtract(min);
int length = range.bitLength();
BigInteger result = new BigInteger(length, RANDOM);
while(result.compareTo(range) >= 0) {
result = new BigInteger(length, RANDOM);
}
result = result.add(min);
return result;
}
Upvotes: 2
Reputation: 693
I have something that I have worked with before
public class RandomString {
private static final Random random = new Random();
public static String numeric(int count) {
if (count == 0) {
return "";
} else if (count < 0) {
throw new IllegalArgumentException("Requested random string length " + count + " is less than 0.");
}
int end = 'z' + 1;
int start = ' ';
char[] buffer = new char[count];
int gap = end - start;
while (count-- != 0) {
char ch;
ch = (char) (random.nextInt(gap) + start);
if (Character.isDigit(ch)) {
if (ch >= 56320 && ch <= 57343) {
if (count == 0) {
count++;
} else {
// low surrogate, insert high surrogate after putting it in
buffer[count] = ch;
count--;
buffer[count] = (char) (55296 + random.nextInt(128));
}
} else if (ch >= 55296 && ch <= 56191) {
if (count == 0) {
count++;
} else {
// high surrogate, insert low surrogate before putting it in
buffer[count] = (char) (56320 + random.nextInt(128));
count--;
buffer[count] = ch;
}
} else if (ch >= 56192 && ch <= 56319) {
// private high surrogate, no effing clue, so skip it
count++;
} else {
buffer[count] = ch;
}
} else {
count++;
}
}
return new String(buffer);
}
}
you can call this class like this
RandomString.numeric(22);
it will do what you want
Upvotes: 0