Count of prime factors of N to be added at each step to convert N to M

Given two integers N and M, the task is to find out minimum number of operations required to convert N to M. Each operation involves adding one of the prime factors of the current value of N. If it is posible to obtain M, print the number of operations. Otherwise, print -1.

Examples:

Input: N = 6, M = 10
Output: 2
Explanation:
Prime factors of 6 are [2, 3].
Adding 2 to N, we obtain 8.
The prime factor of 8 is [2].
Adding 2 to N, we obtain 10, which is the desired result.
Hence, total steps = 2

Input: N = 2, M = 3
Output: -1
Explanation:
There is no way to convert N = 2 to M = 3.

Approach:
The problem can be solved by using BFS to obtain minimum steps to reach M and Sieve of Eratosthenes to precompute prime numbers.
Follow the steps below to solve the problem:



  • Store and precompute all prime numbers using Sieve.
  • Now, if N is already equal to M, print 0 as no addition operation is required.
  • Visualize this problem as a graph problem to perform BFS. At each level store the reachable numbers from the values of N in the previous level by adding prime factors.
  • Now, start by inserting (N, 0), where N denotes the value and 0 denotes the number of operations to reach that value, in the queue initially.
  • At each level of the queue, traverse all elements one by one by extracting the element at the front() and perform the following:
    1. Store q.front().first() in newNum and q.front().second() in distance, where newNum is the current value and distance is the number of operations required to reach this value.
    2. Store all prime factors of newNum in a set.
    3. If newNum is equal to M, then print distance, as it is the minimum operations required.
    4. If newNum is greater than M, then break.
    5. Otherwise, newNum is less than M. So, update newNum by adding its prime factors i one by one and store (newNum + i, distance + 1) in the queue and repeat the above steps for the next level.
  • If the search continues to a level where the queue becomes empty, it means that M cannot be obtained from N. Print -1.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find the minimum
// steps required to convert a number
// N to M.
#include <bits/stdc++.h>
using namespace std;
  
// Array to store shortest prime
// factor of every integer
int spf[100009];
  
// Function to precompute
// shortest prime factors
void sieve()
{
    memset(spf, -1, 100005);
    for (int i = 2; i * i <= 100005; i++) {
        for (int j = i; j <= 100005; j += i) {
            if (spf[j] == -1) {
                spf[j] = i;
            }
        }
    }
}
  
// Function to insert distinct prime factors
// of every integer into a set
set<int> findPrimeFactors(set<int> s,
                          int n)
{
    // Store distinct prime
    // factors
    while (n > 1) {
        s.insert(spf[n]);
        n /= spf[n];
    }
    return s;
}
  
// Function to return minimum
// steps using BFS
int MinimumSteps(int n, int m)
{
  
    // Queue of pairs to store
    // the current number and
    // distance from root.
    queue<pair<int, int> > q;
  
    // Set to store distinct
    // prime factors
    set<int> s;
  
    // Run BFS
    q.push({ n, 0 });
    while (!q.empty()) {
  
        int newNum = q.front().first;
        int distance = q.front().second;
  
        q.pop();
  
        // Find out the prime factors of newNum
        set<int> k = findPrimeFactors(s,
                                      newNum);
  
        // Iterate over every prime
        // factor of newNum.
        for (auto i : k) {
  
            // If M is obtained
            if (newNum == m) {
  
                // Return number of
                // operations
                return distance;
            }
  
            // If M is exceeded
            else if (newNum > m) {
                break;
            }
  
            // Otherwise
            else {
  
                // Update and store the new
                // number obtained by prime factor
                q.push({ newNum + i,
                         distance + 1 });
            }
        }
    }
  
    // If M cannot be obtained
    return -1;
}
  
// Driver code
int main()
{
    int N = 7, M = 16;
  
    sieve();
  
    cout << MinimumSteps(N, M);
}

chevron_right


Output:

2

Time Complexity: O(N* log(N))
Auxiliary Space: O(N)

competitive-programming-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.