考虑圆形轨道,其中n个点标记为1、2,… n。一个人最初放置在点k上。人移动m> 0,在每一步中向前移动(循环)。找到使人到达初始点k所需的最小步数。
例子:
Input : n = 9, k = 2, m = 6
Output : 3
Explanation : Sequence of moves is
2 => 8 => 5 => 2
Input : n = 6, k = 3, m = 2
Output : 3
天真的方法:用“ k”和“ count” = 0初始化计数器“ i”。此外,对于每个迭代增量,将“ count”添加“ m”到“ i”。如果i> n,则取n为模,即i =((i + m)%n) 。如果我等于k,那么计数将是我们的答案。
时间复杂度: O(n)。
高效方法:我们找到GCD(n,m),然后将n除以GCD(n,m)。那将是我们的答案。可以解释为:
现在考虑每个问题的n和m,因为我们知道gcd(n,m)必须除以n,并且商告诉我们,从起始位置(例如0)开始连续m次跳跃(加)m个数字之后,我们再次到达起始位置。
注意:在n个数字的圆形排列中,第n个位置和第0个位置相同。
C++
// C++ program to find minimum steps to reach
// starting position in a circular tour.
#include
using namespace std;
// function for finding minimum steps
int minStroke(int n, int m)
{
// return value n / gcd(n, m)
return (n/__gcd(n, m));
}
// Driver function
int main()
{
int n = 12, k = 5, m = 8;
cout << minStroke(n, m);
return 0;
}
Java
// Java program to find minimum steps to reach
// starting position in a circular tour.
class Test
{
// method for finding minimum steps
static int minStroke(int n, int m)
{
// return value n / gcd(n, m)
return (n/gcd(n, m));
}
// method for gcd
static int gcd(int n, int m) {
if (n == 0 || m == 0)
return 0;
if (n == m)
return n;
if (n > m)
return gcd(n-m, m);
return gcd(n, m-n);
}
// Driver method
public static void main(String args[])
{
int n = 12, k = 5, m = 8;
System.out.println(minStroke(n, m));
}
}
Python3
# Python program to find minimum
# steps to reach starting position
# in a circular tour.
# function for finding minimum steps
def minStroke(n, m):
# return value n / gcd(n, m)
return (n / __gcd(n, m))
# method for gcd
def __gcd(n, m):
if(n == 0 or m == 0):
return 0
if (n == m):
return n
if (n > m):
return __gcd(n-m, m)
return __gcd(n, m-n)
# Driver code
n = 12
k = 5
m = 8
print(minStroke(n, m))
# This code is contributed by Anant Agarwal.
C#
// C# program to find minimum steps to reach
// starting position in a circular tour.
using System;
using System.Collections;
class GFG
{
// method for finding minimum steps
static int minStroke(int n, int m)
{
// return value n / gcd(n, m)
return (n/gcd(n, m));
}
// method for gcd
static int gcd(int n, int m) {
if (n == 0 || m == 0)
return 0;
if (n == m)
return n;
if (n > m)
return gcd(n-m, m);
return gcd(n, m-n);
}
// Driver method
public static void Main()
{
int n = 12, m = 8;
Console.WriteLine(minStroke(n, m));
}
}
// This code is contributed by Sam007
PHP
$b)
return __gcd($a - $b , $b);
return __gcd($a , $b - $a);
}
// function for
// finding minimum steps
function minStroke($n, $m)
{
// return value n / gcd(n, m)
return ($n / __gcd($n, $m));
}
// Driver Code
$n = 12; $k = 5; $m = 8;
echo minStroke($n, $m);
// This code is contributed by anuj_67.
?>
Javascript
输出:
3