4
\$\begingroup\$

I am implementing RSA in java using BigInteger and I have a method to return a random relative prime number based on the modulus m.

The method looks like this:

BigInteger prime = new BigInteger(m.bitLength(),rnd);

    while (prime.compareTo(BigInteger.ZERO) <= 0 || !prime.gcd(m).equals(BigInteger.ONE) )
    {
        prime = new BigInteger(m.bitLength(),rnd);
    }

Is there anyway to make this more efficient? I dont know if recreating an object like this is bad or not.

\$\endgroup\$
  • \$\begingroup\$ At least you can rewrite it as a do ... while loop. Could you be more precise about efficiency? What concrete problems do you have? \$\endgroup\$ – CheatEx May 27 '11 at 15:24
3
\$\begingroup\$

What is m.bitLength, and how often do you get a <= 0 or an gcd-1?

Why do you think creating an object in the loop could be bad? Performance? Memory wise?

An object is ready for garbage collection as soon as it is unreachable and out of scope.

So the second object, if the first one fits the condition, will hide the first one - the first one is out of scope, and unreachable.

For a cheap object like a BigInteger, you may worry if you produce millions and millions of Objects in one second, over and over again. Maybe then, if you experience a performance problem, you can measure and find out, where it happens.

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.