Number from a range [ L , R ] having Kth minimum cost of conversion to 1 by given operations | C # implementation of the above approach ; Function to calculate the cost ; Base case ; Even condition ; Odd condition ; Return cost ; Function to find Kth element ; Array to store the costs ; Sort the array based on cost ; Driver code ; Given range and6 K ; Function call
using System ; using System . Linq ; using System . Collections . Generic ; class GFG { static int func ( int n ) { int count = 0 ; if ( n == 2 n == 1 ) return 1 ; if ( n % 2 == 0 ) count = 1 + func ( n / 2 ) ; if ( n % 2 != 0 ) count = 1 + func ( n * 3 + 1 ) ; return count ; } static void findKthElement ( int l , int r , int k ) { List < int > arr = new List < int > ( ) ; for ( int i = l ; i <= r ; i ++ ) arr . Add ( i ) ; Dictionary < int , int > result = new Dictionary < int , int > ( ) ; foreach ( int i in arr ) { result . Add ( i , func ( i ) ) ; } var myList = result . ToList ( ) ; myList . Sort ( ( pair1 , pair2 ) => pair1 . Value . CompareTo ( pair2 . Value ) ) ; Console . WriteLine ( myList [ 1 ] . Key ) ; } public static void Main ( String [ ] args ) { int l = 12 ; int r = 15 ; int k = 2 ; findKthElement ( l , r , k ) ; } }