// ~/.vim/cpp_template.cpp
#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <limits>
#define REP(i,a,b) for (int i = a; i < b; i++)
// Type Aliases for 1D and 2D vectors with initialization
#define vi(n, val) vector<int>(n, val) // 1D vector of ints with size n, initialized to val
#define vll(n, val) vector<long long>(n, val) // 1D vector of long longs with size n, initialized to val
typedef long long ll;
#define vvi(n, m, val) vector<vector<int>>(n, vector<int>(m, val)) // 2D vector of ints (n x m), initialized to val
#define vvll(n, m, val) vector<vector<long long>>(n, vector<long long>(m, val)) // 2D vector of long longs (n x m), initialized to val
#define LL_INF std::numeric_limits<long long int>::max()
#define INF std::numeric_limits<int>::max()
using namespace std;
template <typename T>
void pV(const std::vector<T>& vec, const std::string& label = "Vector") {
std::cout << label << ": [ ";
for (const auto& elem : vec) {
std::cout << elem << " ";
}
std::cout << "]" << std::endl;
}
void dfs(int s, vector<bool> *visited, vector<int> (*adj)[]) {
if ((*visited)[s]) return;
(*visited)[s] = true;
// process node s
for (auto u: (*adj)[s]) {
dfs(u, visited, adj);
}
}
/*
// DEPTH-FRIRST-SEARCH
vector<int> adj[N];
vector<bool> visited(N, false);
int u, v;
for(int i = 0; i < M;i++){
cin >> u >> v;
u--;
v--;
adj[u].push_back(v);
adj[v].push_back(u);
}
*/
vector<long long> dijkstra(int N, int x, vector<vector<pair<int,int>>> *adj){
vector<bool> processed(N, false);
vector<long long> distance(N, LL_INF);
priority_queue<pair<long long,int>> q;
//for (int i = 1; i <= n; i++) distance[i] = INF;
distance[x] = 0;
q.push({0,x});
while (!q.empty()) {
int a = q.top().second; q.pop();
if (processed[a]) continue;
processed[a] = true;
for (auto u : (*adj)[a]) {
int b = u.first, w = u.second;
if (distance[a]+w < distance[b]) {
distance[b] = distance[a]+w;
q.push({-distance[b],b});
}
}
}
return distance;
}
/*
DIJKSTRA
//vector<vector<pair<int,int>>> adj(N, vector<pair<int, int>>(N));
*/
ll e_gcd(ll a, ll b, ll &x, ll &y) {
if (b == 0) {
x = 1;
y = 0;
return a;
}
ll x1, y1;
ll gcd = e_gcd(b, a % b, x1, y1);
x = y1;
y = x1 - (a / b) * y1;
return gcd;
}
ll m_inv(ll a, ll M) {
ll x, y;
ll gcd = e_gcd(a, M, x, y);
if (gcd != 1) {
return -1;
}
x = (x % M + M) % M;
return x;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
// Your code starts here
ll a, M;
cin >> a >> M;
ll result = m_inv(a, M);
cout << result << endl;
return 0;
}