Codeforces 837E Vasya's Function - 数论
Vasya is studying number theory. He has denoted a function f(a, b) such that:
- f(a, 0) = 0;
- f(a, b) = 1 + f(a, b - gcd(a, b)), where gcd(a, b) is the greatest common divisor of a and b.
Vasya has two numbers x and y, and he wants to calculate f(x, y). He tried to do it by himself, but found out that calculating this function the way he wants to do that might take very long time. So he decided to ask you to implement a program that will calculate this function swiftly.
The first line contains two integer numbers x and y (1 ≤ x, y ≤ 1012).
Print f(x, y).
3 5
3
6 3
1
题目大意 (题目太简洁,不需要大意)
因为,所以最终一定会到达边界情况。
所以我们考虑如果a,b的gcd不为1,那么f(a, b - gcd(a, b))在干的事情相当于把b表示成gcd(a, b) * x的形式,每次递归就相当于就是让x减少某个数,如果设g = gcd(a, b),那么就有f(a. b) = f(a / g, b / g)。
如果a和b的gcd是1,那么我们考虑下一个和a不互质的数。这个数一定是a的某个质因子的倍数,所以我们根号大暴力将a质因数分解,然后for一遍,挨个计算不超过b的最大的是pi的倍数的数,然后继续上面的做法,递归求解。
因为当gcd不为1时,至少为2,所以递归的层数不超过层,因为a至多有log2a个不同的质因子,所以总时间复杂度为。
Code
1 /** 2 * Codeforces 3 * Problem#837E 4 * Accepted 5 * Time: 15ms 6 * Memory: 2048k 7 */ 8 #include <bits/stdc++.h> 9 using namespace std; 10 #ifndef WIN32 11 #define Auto "%lld" 12 #else 13 #define Auto "%I64d" 14 #endif 15 typedef bool boolean; 16 #define smax(a, b) a = max(a, b) 17 template<typename T> 18 inline boolean readInteger(T& u){ 19 char x; 20 int aFlag = 1; 21 while(!isdigit((x = getchar())) && x != '-' && x != -1); 22 if(x == -1) { 23 ungetc(x, stdin); 24 return false; 25 } 26 if(x == '-'){ 27 x = getchar(); 28 aFlag = -1; 29 } 30 for(u = x - '0'; isdigit((x = getchar())); u = (u << 1) + (u << 3) + x - '0'); 31 ungetc(x, stdin); 32 u *= aFlag; 33 return true; 34 } 35 36 #define LL long long 37 38 template<typename T> 39 T gcd(T a, T b) { 40 return (b == 0) ? (a) : (gcd(b, a % b)); 41 } 42 43 LL a, b; 44 45 inline void init() { 46 readInteger(a); 47 readInteger(b); 48 LL g = gcd(a, b); 49 a /= g, b /= g; 50 } 51 52 vector<LL> fac; 53 void getFactor(LL x) { 54 fac.clear(); 55 for(LL i = 2; i * i <= x; i++) { 56 if((x % i) == 0) { 57 while((x % i) == 0) x /= i; 58 fac.push_back(i); 59 } 60 } 61 if(x > 1) fac.push_back(x); 62 } 63 64 LL f(LL a, LL b) { 65 if(b <= 1) return b; 66 getFactor(a); 67 LL near = 0, g; 68 for(int i = 0; i < (signed)fac.size(); i++) 69 smax(near, b / fac[i] * fac[i]); 70 g = gcd(a, near); 71 return b - near + f(a / g, near / g); 72 } 73 74 inline void solve() { 75 printf(Auto, f(a, b)); 76 } 77 78 int main() { 79 init(); 80 solve(); 81 return 0; 82 }