Find gcd ( a ^ n , c ) where a , n and c can vary from 1 to 10 ^ 9 | Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; x = x % p 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 >> 1 y = y / 2 ; Finds GCD of a and b ; Finds GCD of a ^ n and c ; check if c is a divisor of a ; First compute ( a ^ n ) % c ; Now simply return GCD of modulo power and c . ; Driver code
def modPower ( x , y , p ) : NEW_LINE INDENT while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % p NEW_LINE DEDENT x = ( x * x ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT def gcd ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT return gcd ( b , a % b ) NEW_LINE DEDENT def gcdPow ( a , n , c ) : NEW_LINE INDENT if ( a % c == 0 ) : NEW_LINE INDENT return c NEW_LINE DEDENT modexpo = modPower ( a , n , c ) NEW_LINE return gcd ( modexpo , c ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 10248585 NEW_LINE n = 1000000 NEW_LINE c = 12564 NEW_LINE print ( gcdPow ( a , n , c ) ) NEW_LINE DEDENT