Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add or subtract very large numbers without bigint in C#?

Tags:

c#

bigint

So let me start by saying that I'm a newbie with little to moderate knowledge about C#.

Coming to the topic: I need to make a program that is able to add/subtract very large integers. Initially, used BigInt only to find out it's not allowed. There should be a logical workaround for this? I have an idea which is using "elementary school method" where you add each digit starting from right to left.

I made a string which I split into char array and added each digit from right to left(GetUpperBound-i). But it doesn't seem to work.

My Code:

string s, s2;
char[] c_arr, c_arr2;
int i, erg;

s = "1234";
s2 = "5678";
c_arr = s.ToCharArray();
c_arr2 = s2.ToCharArray();
for (i = 0; i <= c_arr.GetUpperBound(0); i++)
{
    erg = c_arr[c_arr.GetUpperBound(0)-i]+c_arr2[c_arr2.GetUpperBound(0)-i];
    Console.Write(erg);
}

Console.ReadKey();
like image 682
Minimax Avatar asked Jan 12 '23 07:01

Minimax


1 Answers

There are a few things wrong with your code for the 'elementary school method'. You don't account for carry, you're adding up ascii values rather than actual values between 0-9, and you're outputting the results in the wrong order.

The code below, whilst not very elegant, does produce the correct results:

var s1 = "12345";
var s2 = "5678";
var carry = false;
var result = String.Empty;

if(s1.Length != s2.Length)
{
    var diff = Math.Abs(s1.Length - s2.Length);

    if(s1.Length < s2.Length)
    {
        s1 = String.Join("", Enumerable.Repeat("0", diff)) + s1;
    }
    else
    {
        s2 = String.Join("", Enumerable.Repeat("0", diff)) + s2;
    }
}


for(int i = s1.Length-1;i >= 0; i--)
{
    var augend = Convert.ToInt32(s1.Substring(i,1));
    var addend = Convert.ToInt32(s2.Substring(i,1));
    var sum = augend + addend;
    sum += (carry ? 1 : 0);
    carry = false;
    if(sum > 9)
    {
        carry = true;
        sum -= 10;
    }

    result = sum.ToString() + result;
}

if(carry)
{
    result = "1" + result;
}

Console.WriteLine(result);
like image 145
Matt Avatar answered Jan 29 '23 16:01

Matt