Given an integer N and an infinite table where ith row and jth column contains the value i *j. The task is to find the minimum number of moves to reach the cell containing N starting from the cell (1, 1).
Note: From (i, j) only valid moves are (i + 1, j) and (i, j + 1)
Input: N = 10
(1, 1) -> (2, 1) -> (2, 2) -> (2, 3) -> (2, 4) -> (2, 5)
Input: N = 7
Approach: Note that any cell (i, j) can be reached in i + j – 2 steps. Thus, only the pair (i, j) is required with i * j = N that minimizes i + j. It can be found out by finding all the possible pairs (i, j) and check them in O(√N). To do this, without loss of generality, it can be assumed that i ≤ j and i ≤ √N since N = i * j ≥ i2. So √N ≥ i2 i.e. √N ≥ i.
Thus, iterate over all the possible values of i from 1 to √N and, among all the possible pairs (i, j), pick the lowest value of i + j – 2 and that is the required answer.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Minimum number of moves required to reach the destination by the king in a chess board
- Find minimum moves to reach target on an infinite line
- Minimum moves to reach target on a infinite line | Set 2
- Minimum time to reach a point with +t and -t moves at time t
- Expected number of moves to reach the end of a board | Dynamic programming
- Expected number of moves to reach the end of a board | Matrix Exponentiation
- Number of ways to reach (X, Y) in a matrix starting from the origin
- Number of ways to reach (M, N) in a matrix starting from the origin without visiting (X, Y)
- Total position where king can reach on a chessboard in exactly M moves
- Total position where king can reach on a chessboard in exactly M moves | Set 2
- Minimum number of given moves required to make N divisible by 25
- Minimum moves taken to move coin of each cell to any one cell of Matrix
- Find minimum moves to bring all elements in one cell of a matrix
- Count minimum moves required to convert A to B
- Minimum steps to come back to starting point in a circular tour
- Minimum number of jumps to reach end
- Find the minimum number of steps to reach M from N
- Paths requiring minimum number of jumps to reach end of array
- Number of triangles after N moves
- Number of moves required to guess a permutation.
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.