H. Csaba H. Csaba - 3 months ago 22
C# Question

c# sum of two really big numbers

My task is to add a very big number to another and print the result.
Here is my implementation, it should give 1000 as output but it writes 0000.

How it should work:
if the two number has equal length:
just /10 for the digit %10 for the remainder. If the length of the result is bigger than the original add the last remainder to the last element of the output array.

if the two number has different length:
sum the intersection part and add the remainder (in temp) to the relative complementl.

What is wrong?

static int[] SumOfBigNumbers(int[] firstNumber, int[] secondNumber)
{
int temp = 0;
int maxLength = (Math.Max(firstNumber.Length, secondNumber.Length));
int minLength = (Math.Min(firstNumber.Length, secondNumber.Length));
int[] output = new int[maxLength + 1];

//sum of equal part
for (int counter = 0; counter < minLength; counter++)
{
output[counter] = (firstNumber[counter] + secondNumber[counter] + temp) % 10;
temp = (firstNumber[counter] + secondNumber[counter] + temp) / 10;
}
//exceptions add the temp to the bigger array
if (temp!=0)
{
//if first array is bigger than the second
if (firstNumber.Length > secondNumber.Length)
{
for (int i = minLength; i < maxLength + 1; i++)
{
output[i] = (firstNumber[i] + temp) % 10;
temp = (firstNumber[i] + temp) / 10;
}
}
//if second array is bigger than the first
else if (firstNumber.Length < secondNumber.Length)
{
for (int i = minLength; i < maxLength + 1; i++)
{
output[i] = (secondNumber[i] + temp) % 10;
temp = (secondNumber[i] + temp) / 10;
}
}
//if two number has equal length but there is temp left
else
{
output[maxLength] = temp;
}
}
return output;
}
static void Main()
{
int[] firstArray = new int[3] { 0, 0, 5 };
int[] secondArray = new int[3] { 0, 0,5 };
int[] output = SumOfBigNumbers(firstArray, secondArray);
foreach (var i in output)
{
Console.WriteLine(output[i]);
}
}


*Edit better if I copy the task: Write a method that calculates the sum of two very long positive integer numbers. The numbers are represented as array digits and the last digit (the ones) is stored in the array at index 0. Make the method work for all numbers with length up to 10,000 digits.

Answer

Your code works fine but you have a small bug where you display the output array.

You do a foreach (var i in output) {, but you use the i as an index, which it isn't. It is already the actual value. Just write the i to the console.

foreach (var i in output)
{
    Console.WriteLine(i);
}

// Output:
// 0
// 0
// 0
// 1

Or use a for loop to go through the array by index.

for (int i = 0; i < output.Length; i++)
{
    Console.WriteLine(output[i]);
}

// Output:
// 0
// 0
// 0
// 1
Comments