Given a positive number N, we need to reach to 1 in minimum number of steps where a step is defined as converting N to (N-1) or converting N to its one of the bigger divisor.
Formally, if we are at N, then in 1 step we can reach to (N – 1) or if N = u*v then we can reach to max(u, v) where u > 1 and v > 1.
Input : N = 17 Output : 4 We can reach to 1 in 4 steps as shown below, 17 -> 16(from 17 - 1) -> 4(from 4 * 4) -> 2(from 2 * 2) -> 1(from 2 - 1) Input : N = 50 Output : 5 We can reach to 1 in 5 steps as shown below, 50 -> 10(from 5 * 10) -> 5(from 2 * 5) -> 4(from 5 - 1) -> 2(from 2 *2) -> 1(from 2 - 1)
We can solve this problem using breadth first search because it works level by level so we will reach to 1 in minimum number of steps where next level for N contains (N – 1) and bigger proper factors of N.
Complete BFS procedure will be as follows, First we will push N with steps 0 into the data queue then at each level we will push their next level elements with 1 step more than its previous level elements. In this way when 1 will be popped out from queue, it will contain minimum number of steps with it, which will be our final result.
In below code a queue of a structure of ‘data’ type is used which stores value and steps from N in it, another set of integer type is used to save ourselves from pushing the same element more than once which can lead to an infinite loop. So at each step, we push the value into set after pushing that into the queue so that the value won’t be visited more than once.
Please see below code for better understanding,
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Reach A and B by multiplying them with K and K^2 at every step
- Minimum number of jumps to reach end
- Minimum steps to reach a destination
- Minimum steps required to reach the end of a matrix | Set 2
- Minimum steps to reach end of array under constraints
- Minimum steps to reach target by a Knight | Set 1
- Find the minimum number of steps to reach M from N
- Minimum steps to reach any of the boundary edges of a matrix | Set-2
- Minimum cost to reach a point N from 0 with two different operations allowed
- Minimum moves to reach target on a infinite line | Set 2
- Find minimum moves to reach target on an infinite line
- Minimum cells traversed to reach corner where every cell represents jumps
- Minimum number of moves required to reach the destination by the king in a chess board
- Minimum steps to reach end from start by performing multiplication and mod operations with array elements
- Minimum time to reach a point with +t and -t moves at time t