Question:
Given 2 integers N and M. Convert a number N to M using minimum number of given operations.
The operations are:
- Square N (N = N^2)
- Divide N by a prime integer P if N is divisible by P (N = N / P and N % P == 0)
Contrants:
N, M <= 10^9
Example:
N = 12, M = 18
The minimum operations are:
- N /= 2 -> N = 6
- N = N^2 -> N = 36
- N /= 2 -> N = 18
My take:
I'm trying to use BFS to solve this problem. For each number, the available edges to other numberers are the operations. But it got Time Limit Exceeded. Is there any better way to solve this?
Here is my BFS code:
queue<pair<int,int> > q;
vector<long long> pr;
ll m,n;
bool prime[MAXN+1];
void solve()
{
while (!q.empty())
{
pii x=q.front();
q.pop();
if (x.first==m)
{
cout << x.second;
return;
}
if (x.first==1) continue;
for(ll k:pr)
{
if (k>x.first) break;
if (x.first%k==0) q.push({x.first/k,x.second+1});
}
q.push({x.first*x.first,x.second+1});
}
}
The algorithm uses the decomposition on
NandMin prime factors, keeping trace of the corresponding exponents.If
Mhas a prime factor thatNdoes not have, there is no solution (the code returns -1).If
Nhas some prime factors thatMdoesn't have, then the first step is to divideNby these primes.The corresponding number of operations is the sum of the corresponding exponents.
At this stage, we get two arrays
AandBcorresponding to the exponents of the common prime factors, forNandM.It is worth noting that at this stage, the values of the primes involved is not relevant anymore, only the exponents matter.
Then one must determine the minimum number of squares (= multiplications by 2 of the exponents).
The is the smallest
ksuch thatA[i] >= 2^k B[i]for all indicesi.The number of multiplications is added to the number of operations only once, as all exponents are multiplied by 2 at the same time.
Last step is to determine, for each pair
(a, b) = (A[i], B[i]), the number of subtractions needed to go fromatob, while implementing exactlykmultiplications by 2. This is performed with the following rules:The complexity is dominated by the decomposition in primes factors: O(sqrt(n))
Code:
This code is rather long, but a great part consists if helper routines needed for debugging and analysis.