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++
#include <bits/stdc++.h>
using namespace std;
int countOperations( int N, int M)
{
bool visited[100001];
fill(visited, visited + 100001, false );
queue<pair< int , int > > Q;
Q.push(make_pair(N, 0));
visited[N] = true ;
while (!Q.empty()) {
int aux = Q.front().first;
int cont = Q.front().second;
Q.pop();
if (aux == M)
return cont;
for ( int i = 2; i * i <= aux; i++)
if (aux % i == 0) {
if (aux + i <= M && !visited[aux + i]) {
Q.push(make_pair(aux + i, cont + 1));
visited[aux + i] = true ;
}
if (aux + aux / i <= M
&& !visited[aux + aux / i]) {
Q.push(
make_pair(aux + aux / i, cont + 1));
visited[aux + aux / i] = true ;
}
}
}
return -1;
}
int main()
{
int N = 4, M = 24;
cout << countOperations(N, M);
return 0;
}
|
Java
import java.util.*;
class GFG{
static class pair<T, V>
{
T first;
V second;
}
static pair<Integer, Integer> make_pair( int f, int s)
{
pair<Integer, Integer> p = new pair<>();
p.first = f; p.second = s;
return p;
}
static int countOperations( int N, int M)
{
boolean [] visited = new boolean [ 100001 ];
Arrays.fill(visited, false );
Queue<pair<Integer, Integer>> Q = new LinkedList<>();
Q.add(make_pair(N, 0 ));
visited[N] = true ;
while (!Q.isEmpty())
{
int aux = Q.peek().first;
int cont = Q.peek().second;
Q.remove();
if (aux == M)
return cont;
for ( int i = 2 ; i * i <= aux; i++)
if (aux % i == 0 )
{
if (aux + i <= M && !visited[aux + i])
{
Q.add(make_pair(aux + i, cont + 1 ));
visited[aux + i] = true ;
}
if (aux + aux / i <= M &&
!visited[aux + aux / i])
{
Q.add(make_pair(aux + aux / i,
cont + 1 ));
visited[aux + aux / i] = true ;
}
}
}
return - 1 ;
}
public static void main(String[] args)
{
int N = 4 , M = 24 ;
System.out.println(countOperations(N, M));
}
}
|
Python3
def countOperations(N, M):
visited = [ False ] * ( 100001 )
Q = []
Q.append([N, 0 ])
visited[N] = True
while ( len (Q) > 0 ):
aux = Q[ 0 ][ 0 ]
cont = Q[ 0 ][ 1 ]
Q.pop( 0 )
if (aux = = M):
return cont
i = 2
while i * i < = aux:
if (aux % i = = 0 ):
if (aux + i < = M and not visited[aux + i]):
Q.append([aux + i, cont + 1 ])
visited[aux + i] = True
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
return - 1
N, M = 4 , 24
print (countOperations(N, M))
|
C#
using System;
using System.Collections;
class GFG
{
static int countOperations( int N, int M)
{
bool [] visited = new bool [100001];
Queue Q = new Queue();
Q.Enqueue( new Tuple< int , int >(N, 0));
visited[N] = true ;
while (Q.Count > 0) {
int aux = ((Tuple< int , int >)(Q.Peek())).Item1;
int cont = ((Tuple< int , int >)(Q.Peek())).Item2;
Q.Dequeue();
if (aux == M)
return cont;
for ( int i = 2; i * i <= aux; i++)
if (aux % i == 0)
{
if (aux + i <= M && !visited[aux + i]) {
Q.Enqueue( new Tuple< int , int >(aux + i, cont + 1));
visited[aux + i] = true ;
}
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 ;
}
}
}
return -1;
}
static void Main ()
{
int N = 4, M = 24;
Console.WriteLine(countOperations(N, M));
}
}
|
Javascript
<script>
function countOperations(N, M)
{
let visited = new Array(100001);
let Q = [];
Q.push([N, 0]);
visited[N] = true ;
while (Q.length > 0) {
let aux = Q[0][0];
let cont = Q[0][1];
Q.shift();
if (aux == M)
return cont;
for (let i = 2; i * i <= aux; i++)
if (aux % i == 0)
{
if (aux + i <= M && !visited[aux + i]) {
Q.push([aux + i, cont + 1]);
visited[aux + i] = true ;
}
if (aux + parseInt(aux / i, 10) <= M
&& !visited[aux + parseInt(aux / i, 10)]) {
Q.push([aux + parseInt(aux / i, 10), cont + 1]);
visited[aux + parseInt(aux / i, 10)] = true ;
}
}
}
return -1;
}
let N = 4, M = 24;
document.write(countOperations(N, M));
</script>
|
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.
- 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.
- 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.
- 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.
- 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.
- 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.
- Iterate through the queue:
Iterate in a range till the queue of pairs q is not empty.
- 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.
- 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.
- Iterate through the range:
Iterate in a range [2, aux/2] and perform the following steps.
- Check if i is a factor of aux:
If i is a factor of aux, then take the following steps.
- 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.
- 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.
- Return -1 if impossible:
If we cannot make N equal to M, return -1.
- Output the result:
The output of the program is the minimum number of moves required to change N to M.
C++
#include <bits/stdc++.h>
using namespace std;
int countOperations( int N, int M)
{
bool visited[100001];
fill(visited, visited + 100001, false );
queue<pair< int , int > > Q;
Q.push(make_pair(N, 0));
visited[N] = true ;
while (!Q.empty()) {
int aux = Q.front().first;
int cont = Q.front().second;
Q.pop();
if (aux == M)
return cont;
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 ;
}
}
}
}
return -1;
}
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 {
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 ;
}
}
}
}
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)
{
bool [] visited = new bool [100001];
Array.Fill(visited, false );
Queue<Tuple< int , int >> Q = new Queue<Tuple< int , int >>();
Q.Enqueue( new Tuple< int , int >(N, 0));
visited[N] = true ;
while (Q.Count > 0)
{
Tuple< int , int > front = Q.Dequeue();
int aux = front.Item1;
int cont = front.Item2;
if (aux == M)
{
return cont;
}
for ( int i = 2; i * i <= aux; i++)
{
if (aux % i == 0)
{
if (aux + i <= M && !visited[aux + i])
{
Q.Enqueue( new Tuple< int , int >(aux + i, cont + 1));
visited[aux + i] = true ;
}
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 ;
}
}
}
}
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 :
visited = [ False ] * (M + 1 )
Q = [(N, 0 )]
visited[N] = True
while Q:
aux, cont = Q.pop( 0 )
if aux = = M:
return cont
for i in range ( 2 , int (aux * * 0.5 ) + 1 ):
if aux % i = = 0 :
if aux + i < = M and not visited[aux + i]:
Q.append((aux + i, cont + 1 ))
visited[aux + i] = True
if aux + aux / / i < = M and not visited[aux + aux / / i]:
Q.append((aux + aux / / i, cont + 1 ))
visited[aux + aux / / i] = True
return - 1
N = 4
M = 24
print (count_operations(N, M))
|
Javascript
function countOperations(N, M) {
const visited = new Array(M + 1).fill( false );
const queue = [[N, 0]];
visited[N] = true ;
while (queue.length) {
const [aux, cont] = queue.shift();
if (aux === M) {
return cont;
}
for (let i = 2; i * i <= aux; i++) {
if (aux % i === 0) {
if (aux + i <= M && !visited[aux + i]) {
queue.push([aux + i, cont + 1]);
visited[aux + i] = true ;
}
if (aux + aux / i <= M && !visited[aux + aux / i]) {
queue.push([aux + aux / i, cont + 1]);
visited[aux + aux / i] = true ;
}
}
}
}
return -1;
}
console.log(countOperations(4, 24));
console.log(countOperations(4, 576));
|
Time Complaxity: O(N*logN)
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...