Number from a range [ L , R ] having Kth minimum cost of conversion to 1 by given operations | 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 ; Given range and K ; Function Call
def func ( n ) : NEW_LINE INDENT count = 0 NEW_LINE if n == 2 or n == 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT if n % 2 == 0 : NEW_LINE INDENT count = 1 + func ( n // 2 ) NEW_LINE DEDENT if n % 2 != 0 : NEW_LINE INDENT count = 1 + func ( n * 3 + 1 ) NEW_LINE DEDENT return count NEW_LINE DEDENT def findKthElement ( l , r , k ) : NEW_LINE INDENT arr = list ( range ( l , r + 1 ) ) NEW_LINE result = [ ] NEW_LINE for i in arr : NEW_LINE INDENT result . append ( [ i , func ( i ) ] ) NEW_LINE DEDENT result . sort ( ) NEW_LINE print ( result [ k - 1 ] [ 0 ] ) NEW_LINE DEDENT l = 12 NEW_LINE r = 15 NEW_LINE k = 2 NEW_LINE findKthElement ( l , r , k ) NEW_LINE