 Open in App
Not now

# Minimum number of moves to make M and N equal by repeatedly adding any divisor of number to itself except 1 and the number

• Last Updated : 24 Feb, 2023

Given two numbers N and M, the task is to find the minimum number of moves to change N to M or -1 if it’s impossible. In one move, add to the current number any of its divisors not equal to 1 and the number itself.

Examples:

Input: N = 4, M = 24
Output: 5
Explanation: the number 24 can be reached starting from 4 using 5 operations: 4->6->8->12->18->24.

Input: N = 4, M = 576
Output: 14

Approach: Build a graph where vertices are numbers from N to M and there is an edge from vertex v1 to vertex v2 if v2 can be obtained from v1 using exactly one operation from the problem statement. To solve the problem, find the shortest path from vertex N to vertex M in this graph. This can be done using the breadth first search algorithm. Follow the steps below to solve the problem:

• Initialize a boolean array visited[] to store whether a particular number is counted or not.
• Fill all the indices of the bool array visited[] with the value false and set the value of visited[N] to true.
• Initialize a queue of pairs q to store the number visited and the number of operations done.
• Push the pair {N, 0} into the queue of pairs q.
• Iterate in a range till the queue of pairs q is not empty.
• Initialize the variables aux as the first value of the front pair of the queue q and cont as the second value of the front pair of the queue q.
• Pop the front pair from the queue of pairs q.
• If aux is equal to M, then, return the value of cont.
• Iterate in a range [2, aux1/2] and perform the following steps.
• If i is a factor of aux, then take the following steps.
• If aux+i is less than equal to M and visited[i+aux] is false, then set the value of visited[aux+i] to true and push the pair {aux+i, cont+1} into the queue of pairs q.
• If aux+aux/i is less than equal to M and visited[aux/i+aux] is false, then set the value of visited[aux+aux/i] to true and push the pair {aux+aux/i, cont+1} into the queue of pairs q.
• Return -1 as it is impossible to make N equal to M.

Below is the implementation of the above approach.

## C++

 `// C++ program for the above approach.` `#include ` `using` `namespace` `std;`   `// Function to find the minimum number` `// of moves to make N and M equal.` `int` `countOperations(``int` `N, ``int` `M)` `{` `    ``// Array to maintain the numbers` `    ``// included.` `    ``bool` `visited;` `    ``fill(visited, visited + 100001, ``false``);`   `    ``// pair of vertex, count` `    ``queue > Q;` `    ``Q.push(make_pair(N, 0));` `    ``visited[N] = ``true``;`   `    ``// run bfs from N` `    ``while` `(!Q.empty()) {` `        ``int` `aux = Q.front().first;` `        ``int` `cont = Q.front().second;` `        ``Q.pop();`   `        ``// if we reached goal` `        ``if` `(aux == M)` `            ``return` `cont;`   `        ``// Iterate in the range` `        ``for` `(``int` `i = 2; i * i <= aux; i++)` `            ``// If i is a factor of aux` `            ``if` `(aux % i == 0) {` `                ``// If i is less than M-aux and` `                ``// is not included earlier.` `                ``if` `(aux + i <= M && !visited[aux + i]) {` `                    ``Q.push(make_pair(aux + i, cont + 1));` `                    ``visited[aux + i] = ``true``;` `                ``}` `                ``// If aux/i is less than M-aux and` `                ``// is not included earlier.` `                ``if` `(aux + aux / i <= M` `                    ``&& !visited[aux + aux / i]) {` `                    ``Q.push(` `                        ``make_pair(aux + aux / i, cont + 1));` `                    ``visited[aux + aux / i] = ``true``;` `                ``}` `            ``}` `    ``}`   `    ``// Not possible` `    ``return` `-1;` `}`   `// Driver Code` `int` `main()` `{`   `    ``int` `N = 4, M = 24;`   `    ``cout << countOperations(N, M);`   `    ``return` `0;` `}`

## Java

 `// Java program for above approach` `import` `java.util.*;`   `class` `GFG{` `    `  `static` `class` `pair` `{` `    ``T first;` `    ``V second;` `}`   `static` `pair make_pair(``int` `f, ``int` `s)` `{` `    ``pair p = ``new` `pair<>();` `    ``p.first = f; p.second = s;` `    ``return` `p;` `}`   `// Function to find the minimum number` `// of moves to make N and M equal.` `static` `int` `countOperations(``int` `N, ``int` `M)` `{` `    `  `    ``// Array to maintain the numbers` `    ``// included.` `    ``boolean``[] visited = ``new` `boolean``[``100001``];` `    ``Arrays.fill(visited, ``false``);`   `    ``// Pair of vertex, count` `    ``Queue> Q = ``new` `LinkedList<>();` `    ``Q.add(make_pair(N, ``0``));` `    ``visited[N] = ``true``;`   `    ``// Run bfs from N` `    ``while` `(!Q.isEmpty()) ` `    ``{` `        ``int` `aux = Q.peek().first;` `        ``int` `cont = Q.peek().second;` `        ``Q.remove();`   `        ``// If we reached goal` `        ``if` `(aux == M)` `            ``return` `cont;`   `        ``// Iterate in the range` `        ``for``(``int` `i = ``2``; i * i <= aux; i++)` `        `  `            ``// If i is a factor of aux` `            ``if` `(aux % i == ``0``) ` `            ``{` `                `  `                ``// If i is less than M-aux and` `                ``// is not included earlier.` `                ``if` `(aux + i <= M && !visited[aux + i])` `                ``{` `                    ``Q.add(make_pair(aux + i, cont + ``1``));` `                    ``visited[aux + i] = ``true``;` `                ``}` `                `  `                ``// If aux/i is less than M-aux and` `                ``// is not included earlier.` `                ``if` `(aux + aux / i <= M && ` `                    ``!visited[aux + aux / i]) ` `                ``{` `                    ``Q.add(make_pair(aux + aux / i,` `                                   ``cont + ``1``));` `                    ``visited[aux + aux / i] = ``true``;` `                ``}` `            ``}` `    ``}` `    `  `    ``// Not possible` `    ``return` `-``1``;` `}`   `// Driver Code` `public` `static` `void` `main(String[] args) ` `{` `    ``int` `N = ``4``, M = ``24``;` `    `  `    ``System.out.println(countOperations(N, M));` `}` `}`   `// This code is contributed by hritikrommie`

## Python3

 `# Python3 program for the above approach.`   `# Function to find the minimum number` `# of moves to make N and M equal.` `def` `countOperations(N, M):` ` `  `    ``# Array to maintain the numbers` `    ``# included.` `    ``visited ``=` `[``False``] ``*` `(``100001``)` `   `  `    ``# Pair of vertex, count` `    ``Q ``=` `[]` `    ``Q.append([N, ``0``])` `    ``visited[N] ``=` `True` `     `  `    ``# Run bfs from N` `    ``while` `(``len``(Q) > ``0``):` `        ``aux ``=` `Q[``0``][``0``]` `        ``cont ``=` `Q[``0``][``1``]` `        ``Q.pop(``0``)` `   `  `        ``# If we reached goal` `        ``if` `(aux ``=``=` `M):` `            ``return` `cont` `   `  `        ``# Iterate in the range` `        ``i ``=` `2` `        `  `        ``while` `i ``*` `i <``=` `aux:` `            `  `            ``# If i is a factor of aux` `            ``if` `(aux ``%` `i ``=``=` `0``):` `                `  `                ``# If i is less than M-aux and` `                ``# is not included earlier.` `                ``if` `(aux ``+` `i <``=` `M ``and` `not` `visited[aux ``+` `i]):` `                    ``Q.append([aux ``+` `i, cont ``+` `1``])` `                    ``visited[aux ``+` `i] ``=` `True` `                `  `                ``# If aux/i is less than M-aux and` `                ``# is not included earlier.` `                ``if` `(aux ``+` `int``(aux ``/` `i) <``=` `M ``and` `not` `                    ``visited[aux ``+` `int``(aux ``/` `i)]):` `                    ``Q.append([aux ``+` `int``(aux ``/` `i), cont ``+` `1``])` `                    ``visited[aux ``+` `int``(aux ``/` `i)] ``=` `True` `                    `  `            ``i ``+``=` `1` `   `  `    ``# Not possible` `    ``return` `-``1`   `# Driver code` `N, M ``=` `4``, ``24` ` `  `print``(countOperations(N, M))`   `# This code is contributed by mukesh07`

## C#

 `// C# program for the above approach.` `using` `System;` `using` `System.Collections;` `class` `GFG` `{` `    `  `    ``// Function to find the minimum number` `    ``// of moves to make N and M equal.` `    ``static` `int` `countOperations(``int` `N, ``int` `M)` `    ``{` `        ``// Array to maintain the numbers` `        ``// included.` `        ``bool``[] visited = ``new` `bool``;` `     `  `        ``// pair of vertex, count` `        ``Queue Q = ``new` `Queue();` `        ``Q.Enqueue(``new` `Tuple<``int``, ``int``>(N, 0));` `        ``visited[N] = ``true``;` `        ``// run bfs from N` `        ``while` `(Q.Count > 0) {` `            ``int` `aux = ((Tuple<``int``,``int``>)(Q.Peek())).Item1;` `            ``int` `cont = ((Tuple<``int``,``int``>)(Q.Peek())).Item2;` `            ``Q.Dequeue();` `     `  `            ``// if we reached goal` `            ``if` `(aux == M)` `                ``return` `cont;` `     `  `            ``// Iterate in the range` `            ``for` `(``int` `i = 2; i * i <= aux; i++)` `              `  `                ``// If i is a factor of aux` `                ``if` `(aux % i == 0)` `                ``{` `                  `  `                    ``// If i is less than M-aux and` `                    ``// is not included earlier.` `                    ``if` `(aux + i <= M && !visited[aux + i]) {` `                        ``Q.Enqueue(``new` `Tuple<``int``, ``int``>(aux + i, cont + 1));` `                        ``visited[aux + i] = ``true``;` `                    ``}` `                  `  `                    ``// If aux/i is less than M-aux and` `                    ``// is not included earlier.` `                    ``if` `(aux + aux / i <= M` `                        ``&& !visited[aux + aux / i]) {` `                        ``Q.Enqueue(``new` `Tuple<``int``, ``int``>(aux + aux / i, cont + 1));` `                        ``visited[aux + aux / i] = ``true``;` `                    ``}` `                ``}` `        ``}` `     `  `        ``// Not possible` `        ``return` `-1;` `    ``}` `    `  `  ``static` `void` `Main ()` `  ``{` `    ``int` `N = 4, M = 24;` ` `  `    ``Console.WriteLine(countOperations(N, M));` `  ``}` `}`   `// This code is contributed by suresh07.`

## Javascript

 ``

Output

`5`

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

Another Approach: Use a more efficient way to generate the factors of a number. Instead of iterating over all numbers in the range [2, aux1/2] to check if they divide the number, we can use a more optimized approach to generate factors.

We can observe that every factor of a number n lies in the range [2, sqrt(n)]. Therefore, we only need to iterate over this range and check if the current number is a factor of n. If it is, we can add both the number and n/number to the queue of pairs.

1. Define the problem:
Given two integers N and M, we need to find the minimum number of moves required to change N to M. In one move, we can add to the current number any of its divisors not equal to 1 and the number itself.
2. Build a graph:
Build a graph where the vertices are the numbers from N to M and there is an edge from vertex v1 to vertex v2 if v2 can be obtained from v1 using exactly one operation from the problem statement.
3. Find the shortest path:
To solve the problem, we need to find the shortest path from vertex N to vertex M in this graph. This can be done using the breadth-first search (BFS) algorithm.
4. Initialize the boolean array:
Initialize a boolean array visited[] to store whether a particular number is counted or not. Fill all the indices of the bool array visited[] with the value false and set the value of visited[N] to true.
5. Initialize the queue:
Initialize a queue of pairs q to store the number visited and the number of operations done. Push the pair {N, 0} into the queue of pairs q.
6. Iterate through the queue:
Iterate in a range till the queue of pairs q is not empty.
7. Dequeue and set variables:
Initialize the variables aux as the first value of the front pair of the queue q and cont as the second value of the front pair of the queue q. Pop the front pair from the queue of pairs q.
8. Check if we have reached the goal:
If aux is equal to M, then return the value of cont, which is the minimum number of moves required to change N to M.
9. Iterate through the range:
Iterate in a range [2, aux/2] and perform the following steps.
10. Check if i is a factor of aux:
If i is a factor of aux, then take the following steps.
11. Check if aux+i is less than equal to M and not visited:
If aux+i is less than equal to M and visited[aux+i] is false, then set the value of visited[aux+i] to true and push the pair {aux+i, cont+1} into the queue of pairs q.
12. Check if aux+aux/i is less than equal to M and not visited:
If aux+aux/i is less than equal to M and visited[aux+aux/i] is false, then set the value of visited[aux+aux/i] to true and push the pair {aux+aux/i, cont+1} into the queue of pairs q.
13. Return -1 if impossible:
If we cannot make N equal to M, return -1.
14. Output the result:
The output of the program is the minimum number of moves required to change N to M.

## C++

 `// C++ program for the above approach.` `#include ` `using` `namespace` `std;` `int` `countOperations(``int` `N, ``int` `M)` `{` `    ``// Array to maintain the numbers` `    ``// included.` `    ``bool` `visited;` `    ``fill(visited, visited + 100001, ``false``);` ` `  `    ``// pair of vertex, count` `    ``queue > Q;` `    ``Q.push(make_pair(N, 0));` `    ``visited[N] = ``true``;` ` `  `    ``// run bfs from N` `    ``while` `(!Q.empty()) {` `        ``int` `aux = Q.front().first;` `        ``int` `cont = Q.front().second;` `        ``Q.pop();` ` `  `        ``// if we reached goal` `        ``if` `(aux == M)` `            ``return` `cont;` ` `  `        ``// Iterate over factors` `        ``for` `(``int` `i = 2; i * i <= aux; i++) {` `            ``if` `(aux % i == 0) {` `                ``int` `factor1 = i;` `                ``int` `factor2 = aux / i;` `                ``if` `(aux + factor1 <= M && !visited[aux + factor1]) {` `                    ``Q.push(make_pair(aux + factor1, cont + 1));` `                    ``visited[aux + factor1] = ``true``;` `                ``}` `                ``if` `(factor1 != factor2 && aux + factor2 <= M && !visited[aux + factor2]) {` `                    ``Q.push(make_pair(aux + factor2, cont + 1));` `                    ``visited[aux + factor2] = ``true``;` `                ``}` `            ``}` `        ``}` `    ``}` ` `  `    ``// Not possible` `    ``return` `-1;` `}` `// Driver Code` `int` `main()` `{`   `    ``int` `N = 4, M = 24;`   `    ``cout << countOperations(N, M);`   `    ``return` `0;` `}`

## Java

 `import` `java.util.Arrays;` `import` `java.util.LinkedList;` `import` `java.util.Queue;`   `public` `class` `MinMovesToChangeNToM {` `    `  `    ``// Function to find the minimum number of moves to change N to M` `    ``// using only allowed operations as described in the problem statement` `    ``public` `static` `int` `countOperations(``int` `N, ``int` `M) {` `        ``boolean``[] visited = ``new` `boolean``[M + ``1``];` `        ``Arrays.fill(visited, ``false``);` `        `  `        ``Queue<``int``[]> queue = ``new` `LinkedList<>();` `        ``queue.offer(``new` `int``[]{N, ``0``});` `        ``visited[N] = ``true``;` `        `  `        ``while` `(!queue.isEmpty()) {` `            ``int``[] pair = queue.poll();` `            ``int` `aux = pair[``0``];` `            ``int` `cont = pair[``1``];` `            `  `            ``if` `(aux == M) {` `                ``return` `cont;` `            ``}` `            `  `            ``for` `(``int` `i = ``2``; i * i <= aux; i++) {` `                ``if` `(aux % i == ``0``) {` `                    ``int` `sum = aux + i;` `                    ``if` `(sum <= M && !visited[sum]) {` `                        ``queue.offer(``new` `int``[]{sum, cont + ``1``});` `                        ``visited[sum] = ``true``;` `                    ``}` `                    ``sum = aux + aux / i;` `                    ``if` `(sum <= M && !visited[sum]) {` `                        ``queue.offer(``new` `int``[]{sum, cont + ``1``});` `                        ``visited[sum] = ``true``;` `                    ``}` `                ``}` `            ``}` `        ``}` `        `  `        ``// Not possible` `        ``return` `-``1``;` `    ``}` `    `  `    ``public` `static` `void` `main(String[] args) {` `        ``int` `N = ``4``, M = ``24``;` `        ``System.out.println(countOperations(N, M));` `    ``}` `}`

## C#

 `using` `System;` `using` `System.Collections.Generic;`   `public` `class` `Solution` `{` `    ``public` `static` `int` `CountOperations(``int` `N, ``int` `M)` `    ``{` `        ``// Array to maintain the numbers included.` `        ``bool``[] visited = ``new` `bool``;` `        ``Array.Fill(visited, ``false``);`   `        ``// Queue of vertex-count pairs.` `        ``Queue> Q = ``new` `Queue>();` `        ``Q.Enqueue(``new` `Tuple<``int``, ``int``>(N, 0));` `        ``visited[N] = ``true``;`   `        ``// Run BFS from N.` `        ``while` `(Q.Count > 0)` `        ``{` `            ``Tuple<``int``, ``int``> front = Q.Dequeue();` `            ``int` `aux = front.Item1;` `            ``int` `cont = front.Item2;`   `            ``// If we reached the goal.` `            ``if` `(aux == M)` `            ``{` `                ``return` `cont;` `            ``}`   `            ``// Iterate over divisors.` `            ``for` `(``int` `i = 2; i * i <= aux; i++)` `            ``{` `                ``// If i is a factor of aux.` `                ``if` `(aux % i == 0)` `                ``{` `                    ``// If i is less than M-aux and is not included earlier.` `                    ``if` `(aux + i <= M && !visited[aux + i])` `                    ``{` `                        ``Q.Enqueue(``new` `Tuple<``int``, ``int``>(aux + i, cont + 1));` `                        ``visited[aux + i] = ``true``;` `                    ``}`   `                    ``// If aux/i is less than M-aux and is not included earlier.` `                    ``if` `(aux + aux / i <= M && !visited[aux + aux / i])` `                    ``{` `                        ``Q.Enqueue(``new` `Tuple<``int``, ``int``>(aux + aux / i, cont + 1));` `                        ``visited[aux + aux / i] = ``true``;` `                    ``}` `                ``}` `            ``}` `        ``}`   `        ``// Not possible.` `        ``return` `-1;` `    ``}`   `    ``public` `static` `void` `Main()` `    ``{` `        ``int` `N = 4, M = 24;`   `        ``Console.WriteLine(CountOperations(N, M));` `    ``}` `}`

## Python3

 `def` `count_operations(N: ``int``, M: ``int``) ``-``> ``int``:` `    ``# Array to maintain the numbers included.` `    ``visited ``=` `[``False``] ``*` `(M ``+` `1``)` ` `  `# pair of vertex, count` `    ``Q ``=` `[(N, ``0``)]` `    ``visited[N] ``=` `True` ` `  `# run bfs from N` `    ``while` `Q:` `        ``aux, cont ``=` `Q.pop(``0``)` ` `  `# if we reached goal` `        ``if` `aux ``=``=` `M:` `            ``return` `cont` ` `  `# Iterate in the range` `        ``for` `i ``in` `range``(``2``, ``int``(aux ``*``*` `0.5``) ``+` `1``):` `            ``# If i is a factor of aux` `            ``if` `aux ``%` `i ``=``=` `0``:` `                ``# If i is less than M-aux and is not included earlier.` `                ``if` `aux ``+` `i <``=` `M ``and` `not` `visited[aux ``+` `i]:` `                    ``Q.append((aux ``+` `i, cont ``+` `1``))` `                    ``visited[aux ``+` `i] ``=` `True` `                ``# If aux/i is less than M-aux and is not included earlier.` `                ``if` `aux ``+` `aux ``/``/` `i <``=` `M ``and` `not` `visited[aux ``+` `aux ``/``/` `i]:` `                    ``Q.append((aux ``+` `aux ``/``/` `i, cont ``+` `1``))` `                    ``visited[aux ``+` `aux ``/``/` `i] ``=` `True` ` `  `# Not possible` `    ``return` `-``1` ` `  `# Example usage` `N ``=` `4` `M ``=` `24` `print``(count_operations(N, M)) ``# Output: 5`

## Javascript

 `function` `countOperations(N, M) {` `  ``// Array to maintain the numbers included` `  ``const visited = ``new` `Array(M + 1).fill(``false``);`   `  ``// Queue of pairs [vertex, count]` `  ``const queue = [[N, 0]];` `  ``visited[N] = ``true``;`   `  ``// Run BFS from N` `  ``while` `(queue.length) {` `    ``const [aux, cont] = queue.shift();`   `    ``// If we reached goal` `    ``if` `(aux === M) {` `      ``return` `cont;` `    ``}`   `    ``// Iterate in the range` `    ``for` `(let i = 2; i * i <= aux; i++) {` `      ``// If i is a factor of aux` `      ``if` `(aux % i === 0) {` `        ``// If i is less than M-aux and is not included earlier` `        ``if` `(aux + i <= M && !visited[aux + i]) {` `          ``queue.push([aux + i, cont + 1]);` `          ``visited[aux + i] = ``true``;` `        ``}` `        ``// If aux/i is less than M-aux and is not included earlier` `        ``if` `(aux + aux / i <= M && !visited[aux + aux / i]) {` `          ``queue.push([aux + aux / i, cont + 1]);` `          ``visited[aux + aux / i] = ``true``;` `        ``}` `      ``}` `    ``}` `  ``}`   `  ``// Not possible` `  ``return` `-1;` `}`   `// Example usage:` `console.log(countOperations(4, 24)); ``// Output: 5` `console.log(countOperations(4, 576)); ``// Output: 14`

Output

`5`

Time Complaxity: O(N*logN)

Auxiliary Space: O(N)

My Personal Notes arrow_drop_up
Related Articles