C++ program to count minimum number of operations needed to make number n to 1

C++Server Side ProgrammingProgramming

Suppose we have a number n. We perform any one of these operations arbitrary number of times −

  • Replace n with n/2 when n is divisible by 2

  • Replace n with 2n/3 when n is divisible by 3

  • Replace n with 4n/5 when n is divisible by 5

We have to count minimum number of moves needed to make number 1. If not possible, return -1.

So, if the input is like n = 10, then the output will be 4, because use n/2 to get 5, then 4n/5 to get 4, then n/2 again to get 2 and n/2 again to get 1.

Steps

To solve this, we will follow these steps −

m := 0
while n is not equal to 1, do:
   if n mod 2 is same as 0, then:
      n := n / 2
      (increase m by 1)
   otherwise when n mod 3 is same as 0, then:
      n := n / 3
      m := m + 2
   otherwise when n mod 5 is same as 0, then:
      n := n / 5
      m := m + 3
   Otherwise
      m := -1
      Come out from the loop
return m

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;

int solve(int n) {
   int m = 0;
   while (n != 1) {
      if (n % 2 == 0) {
         n = n / 2;
         m++;
      }
      else if (n % 3 == 0) {
         n = n / 3;
         m += 2;
      }
      else if (n % 5 == 0) {
         n = n / 5;
         m += 3;
      }
      else {
         m = -1;
         break;
      }
   }

   return m;
}
int main() {
   int n = 10;
   cout << solve(n) << endl;
}

Input

10

Output

4
raja
Updated on 03-Mar-2022 10:20:34

Advertisements