Question

Suppose I do

BigInteger n;

Can I assign any value to n without it overflowing? For instance,

p = new BigInteger(512*512*512, 15, new Random());
n=p;

This is because I made RSA alg. and sometimes it gives me right values, while sometimes it gives me wrong ones and I want to make sure I don't overflow somewhere.

If overflow is the problem, should I, or how should I initialise my BigInts?

Était-ce utile?

La solution

Can I assign any value to n without it overflowing?

There are limits to what a BigInteger can represent. As the javadoc says:

"BigInteger must support values in the range -2Integer.MAX_VALUE (exclusive) to +2Integer.MAX_VALUE (exclusive) and may support values outside of that range."

Later on, it says:

"BigInteger constructors and operations throw ArithmeticException when the result is out of the supported range ..."

... so you don't get unannounced overflows (like you do with primitive integer types) or INF/NaN-like values (like floating point types).


There is also the issue that if the heap is full / too small, creation of a large BigInteger will throw an OOME.


If overflow is the problem ...

In your example, overflow in the BigInteger code it is not the problem. You would be seeing exceptions of some kind.

Furthermore the expression 512*512*512 doesn't overflow. (But in general, you could get an overflow in the constructor argument expressions ... because those calculations are typically done using primitive integer arithmetic, which overflows silently.)

(Pedantically ... the assignment n = p; is a reference assignment, and cannot overflow or throw an OOME. AFAIK, there is no way that it can fail within the context of the Java model. You'd need a hardware error, power failure, heap corruption, code generation bug, etc ...)

Autres conseils

Since you're talking about the RSA algorithm, I suspect this is the code you actually wanted to write:

Random rand = new Random();
BigInteger p = new BigInteger(512, 15, rand);  // A random prime
BigInteger q = new BigInteger(512, 15, rand);  // Another random prime
BigInteger n = p.multiply(q);  // The product of the two primes
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top