My previous posting was about performance of Fibonacci numbers algorithms. In this posting I will introduce you some problems related to limits of our usual integers and introduce you new feature in .Net Framework 4.0 – big integers. Big integers are useful when solving different mathematical problems. Also they are used in cryptography.
As a first thing let’s see the problem we may face when we use our usual integers. Let’s use faster implementation of Fibonacci numbers algorithm so we don’t have to wait a long time to get results we need.C#
Now let’s take some value range where we can expect big numbers as result. Let’s take range from 40 to 50 and compare the results of our algorithm with expected results.
We can see that starting from 47 our results are different. 47 is the point where we go over integer limits and then we go to “next round” in integer scope. Same thing happens also with unsigned integer, long and unsigned long.
If we take some bigger input for our algorithm then we will get even larger numbers. 47 is small number and I am sure that scientific calculations use usually bigger inputs too and breaking over the limits of used type is almost sure.
You may also consider some other algorith that produces faster growth of results. Perfect candidate for this is factorial algorithm. By example 40! = 815915283247897734345611269596115894272000000000.
Introducing BigInteger class
.Net Framework 4.0 solves our problem. New namespace System.Numerics contains class called BigInteger. You can use objects based on this class as usual integers. This class also provides static methods for different mathematical operations on big integers. Let’s move now to BigInteger class with our Fibonacci numbers algorithm.C#
public BigInteger Fibonacci(int x)
var previousValue = new BigInteger(-1);
var currentResult = new BigInteger(1);
for (var i = 0; i <= x; ++i)
var sum = currentResult + previousValue;
previousValue = currentResult;
currentResult = sum;
When we run this code we get expected results.
Some words about BigInteger structure
BigInteger is structure by its nature. It has bunch of static methods that let you perform different mathematical operations on BigIntegers. There are also many operators and type conversions defined for BigInteger so you can use BigIntegers like usual integers. Take look at the BigInteger members documentation.