Find gcd ( a ^ n , c ) where a , n and c can vary from 1 to 10 ^ 9 | CPP program to find GCD of a ^ n and b . ; 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
#include <bits/stdc++.h> NEW_LINE #define ll  long long int NEW_LINE using namespace std ; ll modPower ( ll x , ll y , ll p ) { while ( y > 0 ) { if ( y & 1 ) res = ( res * x ) % p ; x = ( x * x ) % p ; } return res ; } ll gcd ( ll a , ll b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } ll gcdPow ( ll a , ll n , ll c ) { if ( a % c == 0 ) return c ; ll modexpo = modPower ( a , n , c ) ; return gcd ( modexpo , c ) ; } int main ( ) { ll a = 10248585 , n = 1000000 , c = 12564 ; cout << gcdPow ( a , n , c ) ; return 0 ; }