The remainder of ax to m is equal to 1 to the remainder of m -> ax + my = 1 = gcd(a,m)
Just use the extended Euclidean algorithm. When gcd(a,m) is not equal to 1, there is no answer
#include <iostream> using namespace std; typedef long long ll; void ex_gcd(ll a,ll b,ll &x,ll &y,ll &d){ if(!b){ d = a;x = 1;y = 0; } else{ ex_gcd(b,a % b,y,x,d); y -= x * (a / b); } } int main(void){ int t; cin >> t; while(t--){ ll a,m; ll d,x,y; cin >> a >> m; ex_gcd(a,m,x,y,d); if(d == 1){ while(x <= 0){ x += m; } cout << x << endl; } else{ cout << "Not Exist" << endl; } } return 0; }