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
function digSum ( n ) { if ( n == 0 ) return 0 ; return ( n % 9 == 0 ) ? 9 : ( n % 9 ) ; } function powerDigitSum ( a , n ) { let res = 1 ; while ( n ) { if ( n % 2 == 1 ) { res = res * digSum ( a ) ; res = digSum ( res ) ; } a = digSum ( digSum ( a ) * digSum ( a ) ) ; n /= 2 ; } return res ; } let a = 9 , n = 4 ; document . write ( powerDigitSum ( a , n ) ) ;