Given two very large numbers L and R where L ≤ R, the task is to compute the sum of all the natural numbers from L to R. The sum could be large so print the sum % 1000000007.
Input: L = “8894” R = “98592”
Input: L = “88949273204” R = “98429729474298592”
- Let sum(N) is a function that returns the sum of first N natural numbers.
- The sum of the first N natural numbers is sum(N) = (N * (N + 1)) / 2.
- The sum of the numbers in the range between L to R will be RangeSum = sum(R) – sum(L – 1)
- The answer is calculated with the modulo 109 + 7, So,
mod = 109 + 7
RangeSum = (sum(R) – sum(L-1) + mod)%mod;
This can be also written as RangeSum = (sum(R)%mod – sum(L-1)%mod + mod)%mod;
Now, sum(R) % mod can be written as ((R * (R + 1)) / 2) % mod
Or ((R % mod) * ((R + 1) % mod) * invmod(2)) % mod
Since R is large, the modulo of R can be calculated as described here.
The value of inversemod(2) = 500000004 which can be calculated using Fermat’s little theorem.
Similarly, sum(L – 1) % mod can also be calculated.
Below is the implementation of the above approach:
- Comparing X^Y and Y^X for very large values of X and Y
- Dynamic Disjoint Set Data Structure for large range values
- GCD of two numbers when one of them can be very large
- LCM of two large numbers
- Sum of two large numbers
- Difference of two large numbers
- Remainder with 7 for large numbers
- Divisible by 37 for large numbers
- Large Fibonacci Numbers in Java
- Find Last Digit of a^b for Large Numbers
- LCM of First n Natural Numbers
- Natural Numbers
- Sum of first n natural numbers
- Multiply Large Numbers represented as Strings
- Last digit of Product of two Large or Small numbers (a * b)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.