5

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);
    }
Hayes121
  • 283
  • 7
  • 25
  • you can do long num = big.longValue(); if you want to do some calculations on it. – SpaceCowboy Feb 19 '15 at 17:10
  • 2
    This is a bizarre question. Testing a `BigInteger` for primality [is super easy,](http://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html#isProbablePrime-int-) but why could you care if a UUID is prime? I am dying to know. – erickson Feb 19 '15 at 17:16
  • I changed to long but doesnt seem to be 128bits any more, can you suggest anyway to fix that? @durron597 didnt mean to make a duplicate but i think my question is different – Hayes121 Feb 19 '15 at 17:20

1 Answers1

2

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.

Josh
  • 697
  • 6
  • 21