-
Notifications
You must be signed in to change notification settings - Fork 1
/
advancedGCD.cpp
90 lines (61 loc) · 1.45 KB
/
advancedGCD.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Advanced GCD
// Varun explained its friend Sanchit the algorithm of Euclides to calculate the GCD of two numbers. Then Sanchit implements the algorithm
// int gcd(int a, int b)
// {
// if (b==0)
// return a;
// else
// return gcd(b,a%b);
// }
// and challenges to Varun to calculate gcd of two integers, one is a little integer and other integer has 250 digits.
// Your task is to help Varun an efficient code for the challenge of Sanchit.
// Input
// The first line of the input file contains a number representing the number of lines to follow. Each line consists of two number A and B (0 <= A <= 40000 and A <= B < 10^250).
// Output
// Print for each pair (A,B) in the input one integer representing the GCD of A and B..
// Sample Input:
// 2
// 2 6
// 10 11
// Sample Output:
// 2
// 1
#include<iostream>
using namespace std;
int gcd(int a, int b) {
if(b > a) {
return gcd(b, a);
}
if(b == 0) {
return a;
}
return gcd(b, a%b);
}
int getBmodA(string b, int a) {
if(b == "") {
return 0;
}
int len = b.length();
int d = b[len-1] - '0';
string b1 = b.substr(0, len-1);
int smallAns = getBmodA(b1, a);
int ans = ((smallAns * 10%a)%a + d%a)%a;
return ans;
}
int main() {
int t;
cin >> t;
while(t--) {
int a;
string b;
cin >> a;
cin >> b;
if(a == 0) {
cout << b << endl;
continue;
}
int bModA = getBmodA(b, a);
int ans = gcd(a, bModA);
cout << ans << endl;
}
}