只需要考虑 $n < m$ 的情况,因为要求每个人得到的大小一样,所以每次切割都需要对现有的 $n$ 个全部切一次,也就是每次相当于 $n = 2n$,最终要满足 $m | (n \cdot 2^{k})$,要满足这一点,要求 $m$ 的除了 $2$ 之外的质因子,在 $n$ 中也要有,并且 $m$ 中除了 $2$ 的质因子的乘积能够整除 $n$ 中除了 $2$ 的质因子的乘积。这意味着 $\frac{m}{gcd(m, n)}$ 的质因数只有 $2$,也就是它是 $2$ 的幂次。可以利用这一点来判断是否有解。
接下来考虑最小的操作数。要满足 $m | (n \cdot 2^{k})$,而 $m \le 10^9 < 2^{30}$,所以最多操作 $30$ 次。为了让操作次数最小,每次 $n = 2n$ 之后,如果 $n > m$,那么 $n = n \mod m$,也就是每次都把能平均分的苹果都分下去,只留下不能平均分的,这样可以保证最终 $n = m$,同时每次操作 $n$ 的贡献都小于 $m$。
// Date: Thu Dec 28 07:25:02 2023
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
using namespace std;
const int INF = 0x3f3f3f3f, MOD = 1e9 + 7;
const double eps = 1e-8;
const int dir[8][2] = {
{0, 1}, {0, -1}, {1, 0}, {-1, 0}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1},
};
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> VI;
typedef pair<int, int> PII;
const ull Pr = 131;
#define For(i, a, b) for (int i = int(a); i < int(b); ++i)
#define Rof(i, a, b) for (int i = int(b) - 1; i >= int(a); --i)
#define For1(i, a, b) for (int i = int(a); i <= int(b); ++i)
#define Rof1(i, a, b) for (int i = int(b); i >= int(a); --i)
#define ForE(i, j) for (int i = h[j]; i != -1; i = ne[i])
#define f1 first
#define f2 second
#define pb push_back
#define has(a, x) (a.find(x) != a.end())
#define nonempty(a) (!a.empty())
#define all(a) (a).begin(), (a).end()
#define SZ(a) int((a).size())
template <typename t> istream &operator>>(istream &in, vector<t> &vec) {
for (t &x : vec)
in >> x;
return in;
}
template <typename t> ostream &operator<<(ostream &out, vector<t> &vec) {
int n = SZ(vec);
For(i, 0, n) {
out << vec[i];
if (i < n - 1)
out << ' ';
}
return out;
}
#ifdef _DEBUG
#define debug1(x) cout << #x " = " << x << endl;
#define debug2(x, y) cout << #x " = " << x << " " #y " = " << y << endl;
#define debug3(x, y, z) \
cout << #x " = " << x << " " #y " = " << y << " " #z " = " << z << endl;
#else
#define debug1
#define debug2
#define debug3
#endif
ll gcd(ll a, ll b) { return b == 0 ? a : gcd(b, a % b); }
ll lowbit(ll x) { return x & (-x); }
bool count_1(ll x) { return x == lowbit(x); }
int t, n, m;
int main(void) {
#ifdef _DEBUG
freopen("1875c.in", "r", stdin);
#endif
std::ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> t;
while (t--) {
cin >> n >> m;
n = n % m;
if (n == 0) {
cout << "0\n";
continue;
}
ll g = gcd(n, m), m1 = m / g;
if (!count_1(m1)) {
cout << "-1\n";
continue;
}
ll res{};
while (n) {
res += n;
n <<= 1;
n %= m;
}
cout << res << '\n';
}
return 0;
}