Summing Large Numbers

Jake Runzer picture Jake Runzer · May 8, 2012 · Viewed 16.4k times · Source

I have being doing some problems on the Project Euler website and have come across a problem. The Question asks,"Work out the first ten digits of the sum of the following one-hundred 50-digit numbers." I am guessing there is some mathematical way to solve this but I was just wondering how numbers this big are summed? I store the number as a string and convert each digit to a long but the number is so large that the sum does not work.

Is there a way to hold very large numbers as a variable (that is not a string)? I do not want the code to the problem as I want to solve that for myself.

Answer

vid picture vid · May 8, 2012

I was just wondering how numbers this big are summed?

You can use an array:

long LargeNumber[5] = { < first_10_digits>, < next_10_digits>....< last_10_digits> };

Now you can calculate the sum of 2 large numbers:

  long tempSum = 0;
  int carry = 0;
  long sum[5] = {0,0,0,0,0};

  for(int i = 4; i >= 0; i--)
  {
    tempSum = largeNum1[i] + largeNum2[i] + carry; //sum of 10 digits

    if( i == 0)
      sum[i] = tempSum; //No carry in case of most significant digit
    else
      sum[i] = tempSum % 1000000000; //Extra digits to be 'carried over'

    carry = tempSum/1000000000;
  }

  for( int i = 0; i < 5; i++ )
    cout<<setw(10)<<setfill('0')<<sum[i]<<"\n"; //Pad with '0' on the left if needed

Is there a way to hold very large numbers as a variable (that is not a string)?

There's no primitive for this, you can use any data structure (arrays/queues/linkedlist) and handle it suitably

I am guessing there is some mathematical way to solve this

Of course! But,

I do not want the code to the problem as I want to solve that for myself.