Last non | Initialize values of last non - zero digit of numbers from 0 to 9 ; Check whether tens ( or second last ) digit is odd or even If n = 375 , So n / 10 = 37 and ( n / 10 ) % 10 = 7 Applying formula for even and odd cases . ; driver code
dig = [ 1 , 1 , 2 , 6 , 4 , 2 , 2 , 4 , 2 , 8 ] NEW_LINE def lastNon0Digit ( n ) : NEW_LINE INDENT if ( n < 10 ) : NEW_LINE INDENT return dig [ n ] NEW_LINE DEDENT if ( ( ( n // 10 ) % 10 ) % 2 == 0 ) : NEW_LINE INDENT return ( 6 * lastNon0Digit ( n // 5 ) * dig [ n % 10 ] ) % 10 NEW_LINE DEDENT else : NEW_LINE INDENT return ( 4 * lastNon0Digit ( n // 5 ) * dig [ n % 10 ] ) % 10 NEW_LINE DEDENT return 0 NEW_LINE DEDENT n = 14 NEW_LINE print ( lastNon0Digit ( n ) ) NEW_LINE