Codeforces-837E Vasya's Function(gcd)

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;
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值