#include <bits/stdc++.h>
using namespace std;
typedef long long ll ;
void exgcd(ll a , ll b , ll&x , ll&y){
if(b == 0){x = 1 , y = 0 ; return ;}
exgcd(b , a % b , y , x) ;
y -= a / b * x ;
}
ll gcd(ll x , ll y){
if(y == 0) return x ;
gcd(y , x % y) ;
}
int main(){
ios::sync_with_stdio(0);
ll a , b , x , y , t ;
cin>>a>>b;
exgcd(a , b , x , y) ;
t = gcd(a , b) ;
x = (b / t + x % (b / t)) % (b / t) ;
cout<<x;
return 0 ;
}