Created
March 17, 2012 19:13
-
-
Save anaechavarria/2064352 to your computer and use it in GitHub Desktop.
SRM 537 500 Problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| int KingXNewCurrency::howMany(int A, int B, int X) { | |
| int d = __gcd(A, B); | |
| if (d % X == 0) return -1; | |
| set <int> s1; | |
| for (int k = 0; A - k * X >= 0; k++){ | |
| int a = A - k * X; | |
| for (int i = 1; i <= a; i++){ | |
| if (i == X) continue; | |
| if (a % i == 0) s1.insert(i); | |
| } | |
| } | |
| set <int> s2; | |
| for (int k = 0; B - k * X >= 0; k++){ | |
| int b = B - k * X; | |
| for (int i = 1; i <= b; i++){ | |
| if (i == X) continue; | |
| if (b % i == 0) s2.insert(i); | |
| } | |
| } | |
| // If X|A or X|B all of the numbers are divisors | |
| if (A % X == 0) return s2.size(); | |
| if (B % X == 0) return s1.size(); | |
| // Count divisors of A - k * X and B - k * X | |
| set <int> :: iterator it1 = s1.begin(); | |
| set <int> :: iterator it2 = s2.begin(); | |
| int count = 0; | |
| while (it1 != s1.end() and it2 != s2.end()){ | |
| if (*it1 < *it2) it1++; | |
| else if (*it2 < *it1) it2++; | |
| else {count++; it1++; it2++;} | |
| } | |
| return count; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment