Distributing M items in a circle of size N starting from K-th position
M items are to be delivered in a circle of size N. Find the position where the M-th item will be delivered if we start from a given position K. Note that items are distributed at adjacent positions starting from K.
Examples :
Input : N = 5 // Size of circle
M = 2 // Number of items
K = 1 // Starting position
Output : 2
The first item will be given to 1st
position. Second (or last) item will
be delivered to 2nd position
Input : N = 5
M = 8
K = 2
Output : 4
The last item will be delivered to
4th position
We check if the number of items to be distributed is greater than our remaining positions in current cycle of circle or not. If yes, then we simply return m + k – 1 (We distribute items in same cycle starting from k). Else we compute number of remaining items after completing current cycle and return mod of remaining items.
Below is the implementation of the above idea:
C++
#include <bits/stdc++.h>
using namespace std;
int lastPosition( int n, int m, int k)
{
if (m <= n - k + 1)
return m + k - 1;
m = m - (n - k + 1);
return (m % n == 0) ? n : (m % n);
}
int main()
{
int n = 5;
int m = 8;
int k = 2;
cout << lastPosition(n, m, k);
return 0;
}
|
Java
class GFG {
static int lastPosition( int n, int m, int k)
{
if (m <= n - k + 1 )
return m + k - 1 ;
m = m - (n - k + 1 );
return (m % n == 0 ) ? n : (m % n);
}
public static void main(String arg[])
{
int n = 5 ;
int m = 8 ;
int k = 2 ;
System.out.print(lastPosition(n, m, k));
}
}
|
Python3
def lastPosition(n, m, k):
if (m < = n - k + 1 ):
return m + k - 1
m = m - (n - k + 1 )
if (m % n = = 0 ):
return n
else :
return m % n
n = 5
m = 8
k = 2
print (lastPosition(n, m, k))
|
C#
using System;
class GFG {
static int lastPosition( int n, int m, int k)
{
if (m <= n - k + 1)
return m + k - 1;
m = m - (n - k + 1);
return (m % n == 0) ? n : (m % n);
}
public static void Main()
{
int n = 5;
int m = 8;
int k = 2;
Console.WriteLine(lastPosition(n, m, k));
}
}
|
PHP
<?php
function lastPosition( $n , $m , $k )
{
if ( $m <= $n - $k + 1)
return $m + $k - 1;
$m = $m - ( $n - $k + 1);
return ( $m % $n == 0) ? $n : ( $m % $n );
}
$n = 5;
$m = 8;
$k = 2;
echo lastPosition( $n , $m , $k );
?>
|
Javascript
<script>
function lastPosition(n, m, k)
{
if (m <= n - k + 1)
return m + k - 1;
m = m - (n - k + 1);
return (m % n == 0) ? n : (m % n);
}
let n = 5;
let m = 8;
let k = 2;
document.write(lastPosition(n, m, k));
</script>
|
Output :
4
Time Complexity: O(1)
Auxiliary Space: O(1)
Last Updated :
25 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...