/*
ax%b=1
ax+by=1
*/
#include <cstdint>
#include <iostream>

using ll = int64_t;

ll a,b,x,y;

ll exgcd(ll a,ll b){
    if(b==0){
        x=1,y=0;
        return a;
    }
    
    ll d = exgcd(b,a%b);
    ll tmpy = y;
    y=x-a/b*y;
    x=tmpy;
    return d;
}

int main(){
    std::cin>>a>>b;
    exgcd(a,b);
    while (x<0) {
        x=(x%b+b)%b;
    }
    std::cout<<x<<'\n';
}