Sum of Digits in a ^ n till a single digit | This function finds single digit sum of n . ; Returns single digit sum of a ^ n . We use modular exponentiation technique . ; Driver Code
def digSum ( n ) : NEW_LINE INDENT if n == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif n % 9 == 0 : NEW_LINE INDENT return 9 NEW_LINE DEDENT else : NEW_LINE INDENT return n % 9 NEW_LINE DEDENT DEDENT def powerDigitSum ( a , n ) : NEW_LINE INDENT res = 1 NEW_LINE while ( n ) : NEW_LINE INDENT if n % 2 == 1 : NEW_LINE INDENT res = res * digSum ( a ) NEW_LINE res = digSum ( res ) NEW_LINE DEDENT a = digSum ( digSum ( a ) * digSum ( a ) ) NEW_LINE n //= 2 NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a , n = 9 , 4 NEW_LINE print ( powerDigitSum ( a , n ) ) NEW_LINE DEDENT