
Can you solve the problem in logarithmic time and constant space complexity?
The first line of input contains a single integer T, representing the number of test cases or queries to be run.
Then the T test cases follow.
The first line of each test contains two space-separated integers A and B.
For each test case, print a single line containing the GCD of A and B.
1 <= T <= 100
1 <= A <= 10^9
1 <= B <= 10^250
Time Limit: 1sec
You do not need to print anything, it has already been taken care of. Just implement the given function.
In this solution, we will use the fact that GCD of A and B lies between A and B. So we will check all numbers of 1 to A and the largest number which divides both A and B will be our answer.
Here B can have 250 digits to check whether B is divisible by X or not we use the below approach.
We can implement the above approach by –
In this solution, we will use the fact that GCD of A and B belong to the divisor of A.
So we will calculate all divisors of A and the highest divisor of A which divides both A and B will be our answer.
We can calculate all divisors of A in sqrt(A) time complexity by running a loop from 1 to sqrt(A).
To check whether B is divisible by the divisor of A or not we will use the previous approach.
In this solution, we will use the Euclid algorithm.
First, we will do modulo of B with A then we will calculate their GCD using the Euclid algorithm.
Description of the gcd function :
Int gcd(a, b) :
In this solution, we will use the Euclid algorithm.
First, we will do modulo of B with A then we will calculate their GCD using the Euclid algorithm.
Unlike the previous solution this time we will calculate gcd iteratively using loops.
Description of the gcd function :
Int gcd(a, b) :