I wrote this program to calculate very big numbers without using any BigInteger method. I finished it and it’s working properly. I used StringBuilder and lots of parseInt call to get it done. Is there a more efficient way to do this?
By the way, this is just worksheet, ignore bad programming style, after finishing my job, I will reorganize that.
private String add (String x, String y)
{
String g = "";
StringBuilder str = new StringBuilder();
int sum;
double atHand = 0;
int dif = (int)(Math.abs(x.length()-y.length()));
if(x.length() >= y.length()) //adding zero for equalise number of digits.
{
for(int i = 0; i<dif; i++)
g += "0";
y = g+y;
}
else
{
for(int i = 0; i<dif; i++)
g += "0";
x = g + x;
}
for (int i = y.length()-1; i >=0 ; i--)
{
sum = Integer.parseInt(x.substring(i, i+1)) +Integer.parseInt(y.substring(i,i+1)) + (int)atHand;
if(sum<10)
{
str.insert(0, Integer.toString(sum));
atHand = 0;
}else
{
if(i==0)
str.insert(0, Integer.toString(sum));
else
{
atHand = sum *0.1;
sum = sum %10;
str.insert(0, Integer.toString(sum));
}
}
}
return str.toString();
}
Instead of doing it character by character, you should take
kchars at a time, such that it can fit into a Javaintorlong. use some predetermined threshold that can hold both the “block”, and depending on implementation, any overflow (i.e. such that(threshold * 2) < positive_type_limit). To make things easier, use a threshold that is a power of ten, so you can directly map it to characters in a string-representation of a base 10 number (e.g. if your overflow threshold is one million, then you can take 6 characters at a time) – this also have the added benefit that you can efficiently convert it back to a string.Then your “blocks” are much bigger. you would then add and do overflow using these blocks and your limit/threshold (which is based on what integer primitive type you use). So basically you are operating on an array of
ints.You will still have time complexity of
O(n), but it will be a smallern(more specifically, it will beO(n/k)wherekis the number of decimal digits one block represents.)I believe that all solutions involve splitting the big number into smaller blocks and operating on them. You have already done this, just your current solution is the special case of
blocksize=k=1.To get the most of the block, you might use a power of 2 as the limit e.g. for a 32 bit unsigned integer type, you would set your threshold to
2^31(or you could set it to 2^32, but it depends on where and how you are storing the overflow to pass over to the next element).I would not be surprised if BigInteger uses a similar technique.