Find First element in AP which is multiple of given prime | Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; Initialize result ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y / 2 ; function to find nearest element in common ; base conditions ; Driver Code ; module both A and D ; function call
def power ( x , y , p ) : NEW_LINE INDENT res = 1 NEW_LINE x = x % p NEW_LINE while y > 0 : NEW_LINE INDENT if y & 1 : NEW_LINE INDENT res = ( res * x ) % p NEW_LINE DEDENT y = y >> 1 NEW_LINE x = ( x * x ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT def NearestElement ( A , D , P ) : NEW_LINE INDENT if A == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif D == 0 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT X = power ( D , P - 2 , P ) NEW_LINE return ( X * ( P - A ) ) % P NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A , D , P = 4 , 9 , 11 NEW_LINE A %= P NEW_LINE D %= P NEW_LINE print ( NearestElement ( A , D , P ) ) NEW_LINE DEDENT