I'm wanting to add together two really large numbers using C#, without the use of libraries such as BigInterger
. I'm looking at using two strings of numbers and attempting to carry out almost a primary school way of addition by carrying numbers and so on. My code is atrocious and I think that the reason it doesn't work is because I'm not quite understanding what I need to be doing?
string firstNumber = "1769";
string secondNumber = "723";
string product = firstNumber;
int carry = 0;
int positionFirst;
int positionSecond;
for (positionFirst = firstNumber.Length; positionFirst >= 1; positionFirst--)
{
for (positionSecond = secondNumber.Length; positionSecond >= 1; positionSecond--)
{
string currentDigitFirst = firstNumber.Substring(positionFirst - 1, 1);
string currentDigitSecond = secondNumber.Substring(positionSecond - 1, 1);
int intDigitFirst = int.Parse(currentDigitFirst);
int intDigitSecond = int.Parse(currentDigitSecond);
int currentDigitProduct = intDigitFirst + intDigitSecond;
if (carry != 0)
{
currentDigitProduct += carry;
carry /= 10;
}
int currentCarry = currentDigitProduct / 10;
carry += currentCarry;
int numberReplace = currentDigitProduct % 10;
product = product.Remove(positionFirst - 1, 1);
product = product.Insert(positionFirst - 1, numberReplace.ToString());
break;
}
}