E. Vasya's Function
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
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.
Input
The first line contains two integer numbers x and y (1 ≤ x, y ≤ 1012).
Output
Print f(x, y).
Examples
input
3 5
output
3
input
6 3
output
1
设t=gcd(x,y)
①x=k1*t y=k2* t②x=k1*k3*gcd(k1,k2-1) y=k2*k4*gcd(k1,k2-1)
...
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include<set>
#include<vector>
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define first x
#define second y
#define eps 1e-5
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
const int inf = 0x3f3f3f3f;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int MX = 1e6 + 5;
LL gcd(LL a, LL b) {
return b ? gcd(b, a % b) : a;
}
bool a[MX];
vector<LL>ver;
bool pre_solve(LL x) {
for (LL i = 2; i * i <= x; i++)
while (x % i == 0) x /= i, ver.push_back(i);
if (x > 1) ver.push_back(x);
return ver.size() > 1;
}
int main() {
//freopen("in.txt", "r", stdin);
LL x, y;
scanf("%I64d%I64d", &x, &y);
if (pre_solve(x) == 0) {
if (y < x) printf("%I64d\n", y);
else printf("%I64d\n", (y % x) + y / x);
return 0;
}
LL ans = 0;
while (y) {
LL tmp = y;
for (int i = 0; i < ver.size(); i++) tmp = min(tmp, y % ver[i]);
ans += tmp;
y -= tmp;
vector<LL>t;
for (int i = 0; i < ver.size(); i++) {
if (y % ver[i]) t.push_back(ver[i]);
else y /= ver[i];
}
ver.swap(t);
}
printf("%I64d\n", ans);
return 0;
}