-8

Given two very large numbers a and b where a < b, the problem is to find the following sum:

a + (a + 1) + (a + 2) + ... + (b - 2) + (b - 1) + b

The numbers a and b can be very very large (can contain millions of digits).

As these are very large numbers, programming languages cannot find the sum using integer data types. So, the only option is to use strings.

What is the most efficient way to do so?

sanketd617
  • 809
  • 5
  • 16

1 Answers1

3

programming languages cannot find the sum using integer data types. So, the only option is to use strings.

This is false. You can't represent a million-digit integer with a 32-bit or 64-bit int, sure, but it doesn't follow that the best option then is to use strings. You would use a library for dealing with large numbers, see "arbitrary precision arithmetic" -- which lets you represent numbers as large as available memory allows.

In the case of this sum, if m = b-a, you want a*(m+1) + sum(1 ...m) . The sum can be calculated with one multiplication via Gauss's formula. That multiplication can be done in O(n^1.47) where n is the number of digits, the various addition operations are O(n), and I assume division by 2 can be done fast, so the whole time complexity is the time complexity of the multiplications.

jwezorek
  • 8,592
  • 1
  • 29
  • 46