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:
- Find all Factors of Large Perfect Square Natural Number in O(sqrt(sqrt(N))
- Multiply large integers under large modulo
- All possible values of floor(N/K) for all values of K
- Comparing X^Y and Y^X for very large values of X and Y
- Sum of sum of all subsets of a set formed by first N natural numbers
- Sum of all odd natural numbers in range L and R
- Dynamic Disjoint Set Data Structure for large range values
- Difference between Sum of Cubes and Sum of First N Natural Numbers
- Sum of series formed by difference between product and sum of N natural numbers
- Sum of all proper divisors of natural numbers in an array
- Sum of all subsets of a set formed by first n natural numbers
- Sum of all natural numbers in range L to R
- Sum of first N natural numbers with all powers of 2 added twice
- Sum of sum-series of first N Natural numbers
- Check if a given number can be expressed as pair-sum of sum of first X natural numbers
- Print all K digit repeating numbers in a very large number
- Sum of two large numbers
- Sum of two large Floating-point numbers
- Sum of an array of large numbers
- Sum of cubes of even and odd natural numbers
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.