1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| #include <cstdio> #include <algorithm> using namespace std; template <class Type> void read (Type &x) { char c; bool flag = false; while ((c = getchar()) < '0' || c > '9') c == '-' && (flag = true); x = c - '0'; while ((c = getchar()) >= '0' && c <= '9') x = (x << 1) + (x << 3) + c - '0'; flag && (x = ~x + 1); } template <class Type, class ...rest> void read (Type &x, rest &...y) { read(x), read(y...); } template <class Type> void write (Type x) { x < 0 && (putchar('-'), x = ~x + 1); x > 9 && (write(x / 10), 0); putchar('0' + x % 10); } typedef unsigned int UI; typedef unsigned long long ULL; struct Node { ULL f, u, r; Node (ULL _f = 0, ULL _u = 0, ULL _r = 0) : f(_f), u(_u), r(_r) {} friend Node operator * (Node a, Node b) { return Node(a.f + b.f + a.u * b.r, a.u + b.u, a.r + b.r); } }; Node binpow (Node b, UI k) { Node res = Node(); for (; k; k >>= 1, b = b * b) if (k & 1) res = res * b; return res; } Node ugcd(UI a, UI b, UI c, UI n, Node U, Node R) { b %= c; if (a >= c) return ugcd(a % c, b, c, n, U, binpow(U, a / c) * R); UI m = ((ULL)a * n + b) / c; if (m == 0) return binpow(R, n); swap(U, R); return binpow(U, (c - b - 1) / a) * R * ugcd(c, c - b - 1, a, m - 1, U, R) * binpow(U, n - ((ULL)c * m - b - 1) / a); } int main () { UI p, q; read(p, q); Node U = Node(0, 1, 0), R = Node(0, 0, 1); write(ugcd(q, 0, p, p >> 1, U, R).f + ugcd(p, 0, q, q >> 1, U, R).f); return 0; }
|