ANteelauh Farnese - 3 months ago 5

Java Question

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

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
```

Source (Stackoverflow)

Comments