Checking if UUID String is Prime [duplicate] - java

This question already has answers here:
What would be the fastest method to test for primality in Java?
(15 answers)
Closed 8 years ago.
I have created a method to create a 128 bit UUID string, I now want to check if this is a prime number or not. I cant put the string into an int because it is too big. Can anyone suggest how I would go about checking?
This is the code I have used for creating the UUID
public static String uuid()
{
UUID uuid = UUID.randomUUID();
long hi = uuid.getMostSignificantBits();
long lo = uuid.getLeastSignificantBits();
byte[] bytes = ByteBuffer.allocate(16).putLong(hi).putLong(lo).array();
BigInteger big = new BigInteger(bytes);
String numericUuid = big.toString().replace('-','1'); // just in case
//System.out.println(numericUuid);
return(numericUuid);
}

You could use BigInteger's isProbablePrime:
http://www.tutorialspoint.com/java/math/biginteger_isprobableprime.htm
If you pass a high certainty parameter (e.g. 100) then if this returns true, the probability of it actually being a prime number is extremely close to 1.

Related

Generate a random, fixed length BigInteger in Java [duplicate]

This question already has answers here:
How to generate a random BigInteger value in Java?
(8 answers)
Closed 2 years ago.
I am attempting to generate a random 20 digit BigInteger in Java.
So far, I have been able to generate a fixed length hex value.
// generate a user-specified number of random bytes
public void getRandomNumber(int count) {
byte[] bytes = new byte[count];
new SecureRandom().nextBytes(bytes);
String random = new String(Hex.encode(bytes));
System.out.println(random);
}
This is ideal for a fixed length hex generation. But I struggle to find an efficient method of doing this for a decimal representation; when converting from hex to BigInteger(hexValue, 16), the length will vary.
I have considered trying this by setting upper and lower bounds, or by generating something big enough and trimming to the desired length, but those methods do not feel very clean.
Edit: The solution I have came up with that is working fine in my program:
// generate a random number with specified bit length
public void getTokenID() {
int count = 64;
SecureRandom rnd = new SecureRandom();
BigInteger randomCountLength;
String token;
do {
randomCountLength = new BigInteger(count, rnd);
token = randomCountLength.toString();
} while (token.length() != 20);
Tid = token;
}
What I understand that your problem is to generate random number with fixed length (fixed number of digits)
It is obvious that using hex value will work since any hex digit represent 4 bytes. So when you fix the length of bytes (bytes table in your code) it work fine
What I advice you when dealing with decimal number is :
1- There is methods for generating random number with lower and upper bound, for example Random betwen 5 and 10, so if you want for example a random number with 20 digits , you have to generate random number between (10^19) and (10^20-1)
2- The second is hardcoded method to make a loop of 20 iterations when you generate random digit (between 0 and 9 exept the the digit of strong weight which must be between 1 and 9) and you get the number.

check logic 0 in reverse number program in java [duplicate]

This question already has answers here:
Java reverse an int value without using array
(33 answers)
Closed 4 years ago.
This is the logic to reverse a number. But this logic doesn't reverse the number having 0. for example i want to reverse 70 means it will give output as 7.
so kindly give logic to reverse number having 0. Thanks.
while(num>0)
{
rem=num%10;
sum=(sum*10)+rem;
num=num/10;
}
System.out.println("Output is:"+sum );
Integer numbers cannot have leading zeroes.
What would be the use case in which such a function be useful ?
If the purpose is just to reverse an integer number and use it as a string,
then this should do the job.
int num = 70 ;
String numStr = new Integer(num).toString();
StringBuilder numStrB = new StringBuilder(numStr);
String reversedStr = numStrB.reverse().toString();

Converting BigInteger to String, and then back to BigInteger [duplicate]

This question already has answers here:
How to convert BigInteger to String in java
(9 answers)
Closed 6 years ago.
I have code which takes a BigInteger
48451322989516520225703217657832557994348537500303367742400825550923100192302069868489479191146175399344044876949227990959739850227034985347595351425385263774028421913031512265649684935654507691239234667482091135118571200215310568615906290473167269182601320011893758047720172195848415075205065039282385885704
And after I perform bigint.toString(16) I get this string:
44ff39b391fe68e6522d4e2fd99a6c5c77afdae691357f04e5e504790460e7a8e30b3d988e2c1ad316660af7d4e70c012ab711bb77a238f7c2281903523446677f3f26b5d7338c77939f9d97268125adf309aba85e9113f895e9d5179987ab02f3cc255c83e05579664cb08f79390373cb7cce5d280c6647091721567e029a08
which contains letters in it, so after I try and convert it back to a BigInteger I can't b/c it's telling me it's not a number b/c of the letters in the value.
How do you properly go from a BigInteger, to string, and then back to BigInteger? Here is what my code is:
BigInteger decryptedBI = resultBI.modPow(keyD, keyN); // my biginteger
String decrypted = decryptedBI.toString(16); // converted it to a string value
System.out.println(decryptedBI);
System.out.println(decrypted); // this is the decrypted hash
BigInteger has a constructor that takes in a String for the value and an int denoting the radix (in your case, 16).
See the API docs, but here's you how use it:
BigInteger newBI = new BigInteger(myString, 16);

How to generate a unique identifier of a fixed length in Java?

I am trying to generate a unique identifier of a fixed length such as the IDs that are generated by Megaupload for the uploaded files.
For example:
ALGYTAB5
BCLD23A6
In this example using from A-Z and 0-9 and with a fixed length of 8 the total different combinations are 2,821,109,907,456.
What if one of the generated id is already taken. Those ids are going to be stored in a database and it shouldn't be used more than once.
How can I achieve that in Java?
Thank you.
Hmm... You could imitate a smaller GUID the following way. Let first 4 bytes of your string be the encoded current time - seconds passed after Unix. And the last 4 just a random combination. In this case the only way two ID's would coincide is that they were built at the same second. And the chances of that would be very veeery low because of the other 4 random characters.
Pseudocode:
get current time (4 byte integer
id[0] = 1st byte of current time (encoded to be a digit or a letter)
id[1] = 2nd
id[2] = 3rd
id[3] = 4th
id[4] = random character
id[5] = random character
id[6] = random character
id[7] = random character
I have tried #Armen's solution however I would like to give another solution
UUID idOne = UUID.randomUUID();
UUID idTwo = UUID.randomUUID();
UUID idThree = UUID.randomUUID();
UUID idFour = UUID.randomUUID();
String time = idOne.toString().replace("-", "");
String time2 = idTwo.toString().replace("-", "");
String time3 = idThree.toString().replace("-", "");
String time4 = idFour.toString().replace("-", "");
StringBuffer data = new StringBuffer();
data.append(time);
data.append(time2);
data.append(time3);
data.append(time4);
SecureRandom random = new SecureRandom();
int beginIndex = random.nextInt(100); //Begin index + length of your string < data length
int endIndex = beginIndex + 10; //Length of string which you want
String yourID = data.substring(beginIndex, endIndex);
Hope this help!
We're using the database to check whether they already exist. If the number of IDs is low compared to the possible number you should be relatively safe.
You might also have a look at the UUID class (although it's 16-byte UUIDs).
Sounds like a job for a hash function. You're not 100% guaranteed that a hash function will return a unique identifier, but it works most of the time. Hash collisions must be dealt with separately, but there are many standard techniques for you to look into.
Specifically how you deal with collisions depends on what you're using this unique identifier for. If it's a simple one-way identifier where you give your program the ID and it returns the data, then you can simply use the next available ID in the case of a collision.

Cannot convert String to Integer in Java [duplicate]

This question already has answers here:
How do I convert a String to an int in Java?
(47 answers)
Closed 5 years ago.
I have written a function to convert string to integer
if ( data != null )
{
int theValue = Integer.parseInt( data.trim(), 16 );
return theValue;
}
else
return null;
I have a string which is 6042076399 and it gave me errors:
Exception in thread "main" java.lang.NumberFormatException: For input string: "6042076399"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:461)
Is this not the correct way to convert string to integer?
Here's the way I prefer to do it:
Edit (08/04/2015):
As noted in the comment below, this is actually better done like this:
String numStr = "123";
int num = Integer.parseInt(numStr);
An Integer can't hold that value. 6042076399 (413424640921 in decimal) is greater than 2147483647, the maximum an integer can hold.
Try using Long.parseLong.
That's the correct method, but your value is larger than the maximum size of an int.
The maximum size an int can hold is 231 - 1, or 2,147,483,647. Your value is 6,042,076,399. You should look at storing it as a long if you want a primitive type. The maximum value of a long is significantly larger - 263 - 1. Another option might be BigInteger.
That string is greater than Integer.MAX_VALUE. You can't parse something that is out of range of integers. (they go up to 2^31-1, I believe).
In addition to what the others answered, if you have a string of more than 8 hexadecimal digits (but up to 16 hexadecimal digits), you could convert it to a long using Long.parseLong() instead of to an int using Integer.parseInt().

Categories

Resources