Sum of all natural numbers from L to R ( for large values of L and R ) | C ++ implementation of the approach ; Value of inverse modulo 2 with 10 ^ 9 + 7 ; Function to return num % 1000000007 where num is a large number ; Initialize result ; One by one process all the digits of string ' num ' ; Function to return the sum of the integers from the given range modulo 1000000007 ; a stores the value of L modulo 10 ^ 9 + 7 ; b stores the value of R modulo 10 ^ 9 + 7 ; l stores the sum of natural numbers from 1 to ( a - 1 ) ; r stores the sum of natural numbers from 1 to b ; If the result is negative ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define mod  1000000007 NEW_LINE const long long inv2 = 500000004 ; long long int modulo ( string num ) { long long int res = 0 ; for ( long long int i = 0 ; i < num . length ( ) ; i ++ ) res = ( res * 10 + ( long long int ) num [ i ] - '0' ) % mod ; return res ; } long long int findSum ( string L , string R ) { long long int a , b , l , r , ret ; a = modulo ( L ) ; b = modulo ( R ) ; l = ( ( a * ( a - 1 ) ) % mod * inv2 ) % mod ; r = ( ( b * ( b + 1 ) ) % mod * inv2 ) % mod ; ret = ( r % mod - l % mod ) ; if ( ret < 0 ) ret = ret + mod ; else ret = ret % mod ; return ret ; } int main ( ) { string L = "88949273204" ; string R = "98429729474298592" ; cout << findSum ( L , R ) << endl ; return 0 ; }