ANteelauh Farnese ANteelauh Farnese - 1 year ago 113
Java Question

How to divide a BigInteger by integer?

I want to divide a BigInteger by a regular integer (i.e. int) but I don't know how to do this. I did a quick search on Google and on Stack Exchange but didn't find any answers.

So, how can I divide a BigInteger by an int? And while we're at it, how can I add/subtract BigInts to ints, compare BigInts to ints, et cetera?

Answer Source

Accepted answer is working way too hard. Whilst conversion via a String works, it is simply incorrect. No need for intermediate variables either...

Just use BigInteger.valueOf(long) factory method. An int can be implicitly "widened" to be long... This is always the case when going from smaller to large, e.g. byte => short, short => int, int => long.

BigInteger bigInt = BigInteger.valueOf(12);
int regularInt = 6;

BigInteger result = bigInt.divide(BigInteger.valueOf(regularInt));

System.out.println(result); // => 2
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download