Reduce a number to 1 by performing given operations in C++

C++Server Side ProgrammingProgramming

Given an integer Number as input. The goal is to find the minimum number of steps or operations required to reduce the input Number to 1. Operations that can be performed will be-:

  • If Number is even, then Divide it by 2.

  • If Number is odd, then increment or decrement it by 1.

Examples

Input − Number=28

Output − Minimum steps to reduce 28 to 1: 6

Explanation

28 is even - divide by 2 = 14

14 is even - divide by 2 = 7

7 is odd - increment by 1 = 8

8 is even - divide by 2 = 4

4 is even - divide by 2 = 2

2 is even - divide by 2 = 1

Input − Number=9

Output − Minimum steps to reduce 9 to 1: 4

Explanation

9 is odd - decrement by 1 = 8

8 is even - divide by 2 = 4

4 is even - divide by 2 = 2

2 is even - divide by 2 = 1

Approach used in the below program is as follows

In this approach use a recursive approach to check minimum operations required to reduce Number to 1. In case it is even simply divide by 2 else check recursively for minimum ways for Number+1 or Number-1, whichever is less.

  • Take the input Number as integer.

  • Function minWays(int num) takes num as input and returns the count of minimum operations required to reduce num to 1.

  • Take variables tmp1, tmp2 and min as integers.

  • If num is 0 then return 1.

  • If num%2==0 then it is even then set num=num/2

  • If num is odd then set tmp1=minWays(num-1) and tmp2=minWays(num+1).

  • Set min is minimum of tmp1 and tmp2.

  • Return 1+min.

  • At the end we will get the desired result.

  • Print result in main.

Example

#include <iostream>
using namespace std;
int minWays(int num){
   int tmp1,tmp2,min;
   if (num == 1){
      return 0;
   }
   else if (num % 2 == 0){
      tmp1=minWays(num/2);
      return (1 + tmp1);
   }
   else{
      int tmp1=minWays(num - 1);
      int tmp2=minWays(num + 1);
      int min=tmp1<tmp2?tmp1:tmp2;
      return (1 + min);
   }
}
int main(){
   int Number = 21;
   cout <<"Minimum steps to reduce "<<Number<<" to 1: "<<minWays(Number);
   return 0;
}

Output

If we run the above code it will generate the following Output

Minimum steps to reduce 21 to 1: 6
raja
Published on 03-Nov-2021 05:35:13
Advertisements