Minimum steps to reach N from 1 by multiplying each step by 2, 3, 4 or 5
Given an integer N, the task is to find the minimum number of steps to reach the number N from 1 by multiplying each step by 2, 3, 4 or 5. If it is not possible to reach N, print -1.
Input: N = 10
Initial number = 1
Step 1: Multiply it by 2, Current Number = 2
Step 2: Multiply it by 5, Current Number = 10
Therefore, Minimum 2 steps required to reach 10.
Input: N = 13
There is no way reach 13 using any given operations
Attention reader! All those who say programming isn't for kids, just haven't met the right mentors yet. Join the Demo Class for First Step to Coding Course, specifically designed for students of class 8 to 12.
The students will get to learn more about the world of programming in these free classes which will definitely help them in making a wise career choice in the future.
Approach: The idea is to use Greedy Alogorithm to choose the operation that should be performed at each step and perform the operations in the reverse manner that is instead of going from 1 to N, find the operations required to reach N to 1. Below is the illustration of the steps:
- Apply the operations below until N is greater than 1.
- Check if N is divisible by 5, Then increase steps by 1 and reduce N to N/5
- Else, check if N is divisible by 4, Then increase steps by 1 and reduce N to N/4
- Else, check if N is divisible by 3, Then increase steps by 1 and reduce N to N/3
- Else, check if N is divisible by 2, Then increase steps by 1, and reduce N to N/2
- If at any step no operation can be applied then there is no possible set of operations to reach N from 1. Therefore, return -1.
Below is the implementation of the above approach: