Minimum number of moves to reach N starting from (1, 1)
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)
Examples:
Input: N = 10
Output: 5
(1, 1) -> (2, 1) -> (2, 2) -> (2, 3) -> (2, 4) -> (2, 5)
Input: N = 7
Output: 6
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:
C++
#include <bits/stdc++.h>
using namespace std;
int min_moves( int n)
{
int ans = INT_MAX;
for ( int i = 1; i * i <= n; i++) {
if (n % i == 0) {
ans = min(ans, i + n / i - 2);
}
}
return ans;
}
int main()
{
int n = 10;
cout << min_moves(n);
return 0;
}
|
Java
class GFG
{
static int min_moves( int n)
{
int ans = Integer.MAX_VALUE;
for ( int i = 1 ; i * i <= n; i++)
{
if (n % i == 0 )
{
ans = Math.min(ans, i + n / i - 2 );
}
}
return ans;
}
public static void main(String[] args)
{
int n = 10 ;
System.out.println(min_moves(n));
}
}
|
Python3
import sys
from math import sqrt
def min_moves(n) :
ans = sys.maxsize;
for i in range ( 1 , int (sqrt(n)) + 1 ) :
if (n % i = = 0 ) :
ans = min (ans, i + n / / i - 2 );
return ans;
if __name__ = = "__main__" :
n = 10 ;
print (min_moves(n));
|
C#
using System;
class GFG
{
static int min_moves( int n)
{
int ans = int .MaxValue;
for ( int i = 1; i * i <= n; i++)
{
if (n % i == 0)
{
ans = Math.Min(ans, i + n / i - 2);
}
}
return ans;
}
public static void Main(String[] args)
{
int n = 10;
Console.WriteLine(min_moves(n));
}
}
|
Javascript
<script>
function min_moves(n)
{
let ans = Number.MAX_VALUE;
for (let i = 1; i * i <= n; i++)
{
if (n % i == 0)
{
ans = Math.min(ans, i + parseInt(n / i, 10) - 2);
}
}
return ans;
}
let n = 10;
document.write(min_moves(n));
</script>
|
Time Complexity: O(sqrt(n))
Auxiliary Space: O(1), since no extra space has been taken.
Last Updated :
20 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...