Store all values of a ^ ( n * i ) of LHS
for ( int i = 1 , cur = an ; i <= n ; ++ i ) { if ( ! value [ cur ] ) value [ cur ] = i ; cur = ( cur * an ) % m ; } for ( int i = 0 , cur = b ; i <= n ; ++ i ) {