Big integers in C#

As of .NET 4.0 you can use the System.Numerics.BigInteger class. See documentation here: http://msdn.microsoft.com/en-us/library/system.numerics.biginteger(v=vs.110).aspx Another alternative is the IntX class. IntX is an arbitrary precision integers library written in pure C# 2.0 with fast – O(N * log N) – multiplication/division algorithms implementation. It provides all the basic operations on integers like addition, multiplication, comparing, … Read more

Long vs BigInteger

BigInteger is capable of holding far bigger numbers than Long. BigInteger seems capable of holding (2 ^ 32) ^ Integer.MAX_VALUE, though that depends on the implementation (and, even if truly unbounded in the implementation, there will eventually be a physical resource limit) See explanation here. The range of Long is [-9,223,372,036,854,775,808, +9,223,372,036,854,775,807]. Long will perform … Read more

How to generate a random BigInteger value in Java?

Use a loop: BigInteger randomNumber; do { randomNumber = new BigInteger(upperLimit.bitLength(), randomSource); } while (randomNumber.compareTo(upperLimit) >= 0); on average, this will require less than two iterations, and the selection will be uniform. Edit: If your RNG is expensive, you can limit the number of iterations the following way: int nlen = upperLimit.bitLength(); BigInteger nm1 = … Read more

How to handle very large numbers in Java without using java.math.BigInteger

I think a programmer should have implemented his own bignum-library once, so welcome here. (Of course, later you’ll get that BigInteger is better, and use this, but it is a valuable learning experience.) (You can follow the source code of this course life on github. Also, I remade this (a bit polished) into a 14-part … Read more

How to implement big int in C++

A fun challenge. 🙂 I assume that you want integers of arbitrary length. I suggest the following approach: Consider the binary nature of the datatype “int”. Think about using simple binary operations to emulate what the circuits in your CPU do when they add things. In case you are interested more in-depth, consider reading this … Read more

Large Numbers in Java

You can use the BigInteger class for integers and BigDecimal for numbers with decimal digits. Both classes are defined in java.math package. Example: BigInteger reallyBig = new BigInteger(“1234567890123456890”); BigInteger notSoBig = new BigInteger(“2743561234”); reallyBig = reallyBig.add(notSoBig);