Find gcd(a^n, c) where a, n and c can vary from 1 to 10^9 in C++


We have to find the GCD of two numbers of which one number can be as big as (109 ^ 109), which cannot be stored in some data types like long or any other. So if the numbers are a = 10248585, n = 1000000, b = 12564, then result of GCD(a^n, b) will be 9.

As the numbers are very long, we cannot use the Euclidean algorithm. We have to use the modular exponentiation with O(log n) complexity.

Example

 Live Demo

#include<iostream>
#include<algorithm>
using namespace std;
long long power(long long a, long long n, long long b) {
   long long res = 1;
   a = a % b;
   while (n > 0) {
      if (n & 1)
         res = (res*a) % b;
      n = n>>1;
      a = (a*a) % b;
   }
   return res;
}
long long bigGCD(long long a, long long n, long long b) {
   if (a % b == 0)
      return b;
   long long exp_mod = power(a, n, b);
   return __gcd(exp_mod, b);
}
int main() {
   long long a = 10248585, n = 1000000, b = 12564;
   cout << "GCD value is: " << bigGCD(a, n,b);
}

Output

GCD value is: 9

Updated on: 19-Dec-2019

41 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements