GCD of two numbers when one of them can be very large


Given two numbers ‘a’ and ‘b’ such that (0 <= a <= 10^12 and b <= b < 10^250). Find the GCD of two given numbers.


Input: a = 978 
       b = 89798763754892653453379597352537489494736
Output: 6

Input: a = 1221 
       b = 1234567891011121314151617181920212223242526272829
Output: 3

Solution : In the given problem, we can see that first number ‘a’ can be handled by long long int data type but second number ‘b’ can not be handled by any int data type. Here we read second number as a string and we will try to make it less than and equal to ‘a’ by taking it’s modulo with ‘a’ see this, so that we can calculate gcd by using Euclidean Algorithms.

Below is C++ implementation of the above idea.

// C++ program to find GCD of two numbers such that
// the second number can be very large.
using namespace std;
typedef long long int ll;

// function to find gcd of two integer numbers
ll gcd(ll a, ll b)
    if (!a)
       return b;
    return gcd(b%a,a);

// Here 'a' is integer and 'b' is string.
// The idea is to make the second number (represented
// as b) less than and equal to first number by
// calculating its mod with first integer number
// using basic mathematics
ll reduceB(ll a, char b[])
    // Initialize result
    ll mod = 0;

    // calculating mod of b with a to make
    // b like 0 <= b < a
    for (int i=0; i<strlen(b); i++)
        mod = (mod*10 + b[i] - '0')%a;

    return mod; // return modulo

// This function returns GCD of 'a' and 'b'
// where b can be very large and is represented
// as a character array or string
ll gcdLarge(ll a, char b[])
    // Reduce 'b' (second number) after modulo with a
    ll num = reduceB(a, b);

    // gcd of two numbers
    return gcd(a, num);

// Driver program
int main()
    // first number which is integer
    ll a = 1221;

    // second number is represented as string because
    // it can not be handled by integer data type
    char b[] = "1234567891011121314151617181920212223242526272829";

    cout << gcdLarge(a, b);

    return 0;



This article is contributed by Shashank Mishra (Gullu).This article is reviewed by team GeeksforGeeks . Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:

3.6 Average Difficulty : 3.6/5.0
Based on 21 vote(s)

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.