Sum of all natural numbers from L to R ( for large values of L and R ) | Python3 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
mod = 1000000007 NEW_LINE inv2 = 500000004 ; NEW_LINE def modulo ( num ) : NEW_LINE INDENT res = 0 ; NEW_LINE DEDENT ' NEW_LINE INDENT for i in range ( len ( num ) ) : NEW_LINE INDENT res = ( res * 10 + int ( num [ i ] ) - 0 ) % mod ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT def findSum ( L , R ) : NEW_LINE INDENT a = modulo ( L ) ; NEW_LINE b = modulo ( R ) ; NEW_LINE l = ( ( a * ( a - 1 ) ) % mod * inv2 ) % mod ; NEW_LINE r = ( ( b * ( b + 1 ) ) % mod * inv2 ) % mod ; NEW_LINE ret = ( r % mod - l % mod ) ; NEW_LINE if ( ret < 0 ) : NEW_LINE INDENT ret = ret + mod ; NEW_LINE DEDENT else : NEW_LINE INDENT ret = ret % mod ; NEW_LINE DEDENT return ret ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT L = "88949273204" ; NEW_LINE R = "98429729474298592" ; NEW_LINE print ( findSum ( L , R ) ) ; NEW_LINE DEDENT