Find the last digit of given series | Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; x = x % p ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 ; y = y / 2 ; Returns modulo inverse of a with respect to m using extended Euclid Algorithm ; q is quotient ; m is remainder now , process same as Euclid 's algo  ; Make x1 positive ; Function to calculate the above expression ; Initialize the result ; Compute first part of expression ; Compute second part of expression i . e . , ( ( 4 ^ ( n + 1 ) - 1 ) / 3 ) mod 10 Since division of 3 in modulo can ' t ▁ ▁ ▁ be ▁ performed ▁ directly ▁ therefore ▁ we ▁ ▁ ▁ need ▁ to ▁ find ▁ it ' s modulo Inverse ; Driver code
def powermod ( x , y , p ) : NEW_LINE INDENT while ( y > 0 ) : NEW_LINE INDENT if ( ( y & 1 ) > 0 ) : NEW_LINE INDENT res = ( res * x ) % p ; NEW_LINE DEDENT x = ( x * x ) % p ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT def modInverse ( a , m ) : NEW_LINE INDENT m0 = m ; NEW_LINE x0 = 0 ; NEW_LINE x1 = 1 ; NEW_LINE if ( m == 1 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT while ( a > 1 ) : NEW_LINE INDENT q = int ( a / m ) ; NEW_LINE t = m ; NEW_LINE m = a % m ; NEW_LINE a = t ; NEW_LINE t = x0 ; NEW_LINE x0 = x1 - q * x0 ; NEW_LINE x1 = t ; NEW_LINE DEDENT if ( x1 < 0 ) : NEW_LINE INDENT x1 += m0 ; NEW_LINE DEDENT return x1 ; NEW_LINE DEDENT def evaluteExpression ( n ) : NEW_LINE INDENT firstsum = 0 ; NEW_LINE mod = 10 ; NEW_LINE i = 2 ; NEW_LINE j = 0 ; NEW_LINE while ( ( 1 << j ) <= n ) : NEW_LINE INDENT firstsum = ( firstsum + i ) % mod ; NEW_LINE i *= i ; NEW_LINE j += 1 ; NEW_LINE DEDENT secondsum = ( powermod ( 4 , n + 1 , mod ) - 1 ) * modInverse ( 3 , mod ) ; NEW_LINE return ( firstsum * secondsum ) % mod ; NEW_LINE DEDENT n = 3 ; NEW_LINE print ( evaluteExpression ( n ) ) ; NEW_LINE n = 10 ; NEW_LINE print ( evaluteExpression ( n ) ) ; NEW_LINE