Distributing M items in a circle of size N starting from K | n == > Size of circle m == > Number of items k == > Initial position ; n - k + 1 is number of positions before we reach beginning of circle . If m is less than this value , then we can simply return ( m - 1 ) th position ; Let us compute remaining items before we reach beginning . ; We compute m % n to skip all complete rounds . If we reach end , we return n else we return m % n ; Driver code
< ? 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 ) ; ? >