Horje
Parity of final value after repeated circular removal of Kth Integer

Given an integer N, denoting the size of a circle where first N integers are placed in clockwise order such that j and (j+1) are adjacent, and 1 and N are also adjacent. Given an integer K (K < N), the task is to find if the last remaining value is odd or even when in each turn the Kth element from the start (i.e., 1) is removed and it is performed till only one element remains,

Examples:

Input: N = 5, K = 1
Output: Odd
Explanation: Here K = 1 it means first position element is removed from 5 integer circular array i.e. [ 1, 2, 3, 4, 5]→[2, 3, 4, 5] and repeat this step until only one integer remains i.e.[ 2, 3, 4, 5]→[ 3, 4, 5]→[ 4, 5]→[5]. Hence last integer is odd.

Input: N = 3, K = 3
Output: Even

 

Approach: The problem can be solved based on the following observation:

Observations:

  • If K = 1: All numbers from 1 to N-1 are deleted and only N remains
  • If K = 2: All numbers from 2 to N are deleted and only 1 remains.
  • If K > 2: All numbers from K to N are deleted. Remaining numbers are from 1 to K-1. So in each turn  when elements are deleted it follows pattern like 1, 3, 5, . . . because the size of the list decreases by 1 after each iteration and total numbers till the next odd number also decreases by 1. So all the odd elements get deleted first and then the even values. So the last remaining value is always an even number.

Follow the steps mentioned below to implement the observation:

  • Check the value of K and N.
  • Based on their values, decide which of the above cases is applicable.
  • Return the parity of the element thus obtained.

Below is the implementation of the above approach:

C++

<?php
  // Function to find the parity of the last element
  function parity($N, $K)
  {
    if (($K == 1 && ($N % 2 != 0)) || $K == 2)
      return 1;
    return 0;
  }
 
  // Driver code
  $N = 5;
  $K = 1;
 
  // Function call
  if (parity($N, $K)!=0)
    echo "Odd";
  else
    echo "Even";
 
// This code is contributed by rohit768.
?>

Output

Odd

Time Complexity: O(1)
Auxiliary Space: O(1)




Reffered: https://www.geeksforgeeks.org


Mathematical

Related
Find minimum and maximum number of terms to divide N as sum of 4 or 6 Find minimum and maximum number of terms to divide N as sum of 4 or 6
Compute nCr % p | Set 4 (Chinese Remainder theorem with Lucas Theorem) Compute nCr % p | Set 4 (Chinese Remainder theorem with Lucas Theorem)
Find the largest co-prime fraction less than the given fraction Find the largest co-prime fraction less than the given fraction
Probability of hitting the target Nth time at Mth throw Probability of hitting the target Nth time at Mth throw
Count arrangements of N people around circular table such that K people always sit together Count arrangements of N people around circular table such that K people always sit together

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
16