# 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-(a, b))$, where $(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.

## 题意概述

\begin{align} f(a, 0)&=0 \\ f(a, b)&=1+f(a, b-(a, b)) \end{align}

## 代码

import std.stdio;
import std.math;

static immutable int N = 13;

uint top;
long x, y, p, q, ans;
long[N] prime, cnt;

long gcd(long a, long b) {
return b ? gcd(b, a % b) : a;
}

int main() {
p = x, q = cast(long) sqrt(real(x));
for (int i = 2; i <= q; ++ i) {
while (! (p % i)) {
p /= i;
if (prime[top] == i) ++ cnt[top];
else prime[++ top] = i, cnt[top] = 1;
}
}
if (p > 1) prime[++ top] = p, cnt[top] = 1;
while (y) {
long max = 0;
for (int i = 1; i <= top; ++ i)
if (cnt[i])
if (y / prime[i] * prime[i] > max)
max = y / prime[i] * prime[i];
ans += y - max, y = max;
long g = gcd(x, y);
x /= g, y /= g;
for (int i = 1; i <= top; ++ i)
while (! (g % prime[i]))
g /= prime[i], -- cnt[i];
}
writeln(ans);
return 0;
}


418 I'm a teapot