Sum of all natural numbers from L to R ( for large values of L and R ) | Javascript 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 longegers 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
let mod = 1000000007 ; let inv2 = 500000004 ; function modulo ( num ) { let res = 0 ; for ( let i = 0 ; i < num . length ; i ++ ) res = ( res * 10 + num [ i ] . charCodeAt ( ) - ' ' . charCodeAt ( ) ) % mod ; return res ; } function findSum ( L , R ) { let 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 - 6 ; return ret ; } let L = " " ; let R = " " ; document . write ( findSum ( L , R ) ) ;