Reduce the number B to a small number using Fermat Little
for ( int i = 0 ; i < b . length ( ) ; i ++ ) remainderB = ( remainderB * 10 + b . charAt ( i ) - '0' ) % ( MOD - 1 ) ; System . out . println ( power ( a , remainderB , MOD ) ) ; } }