
You are given two integers A and B, where A is a small integer and B can have at most 250 digits. Your task is to find GCD(A, B), where GCD is Greatest Common Divisor.
Follow Up :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.
Output format :
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
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
2
3 1
50 25
1
25
For the first test case,
A = 3 and B = 1
So GCD (3, 1) = 1
For the second test case
A = 50 and B = 25
So GCD(50, 25) = 25
2
5 555555555555555555555555555555555555555
1 232222244444222223444222222422444444444424
5
1
For the first test case,
A = 5 and B = 555555555555555555555555555555555555555
So GCD(A, B) = 5 since 5 is the largest number which divides both A and B.
For the second test case
A = 1 and B = 232222244444222223444222222422444444444424
So GCD(A, B) = 1 since GCD of any number with 1 is 1 itself.
Think of a solution using brute force.
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 –
O(A * D), where A is the number given in the problem, and D is the total number of digits in number B.
In the worst case, we are running a loop from 1 to A which takes O(A) time and checking if x divides B or not takes O(D) time. Hence the overall complexity will be O(A*D).
O(1).
In the worst case, a constant space is required.