Number from a range [ L , R ] having Kth minimum cost of conversion to 1 by given operations | C ++ 14 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int func ( int n ) { int count = 0 ; if ( n == 2 or 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 ; } void findKthElement ( int l , int r , int k ) { vector < int > arr ; for ( int i = l ; i <= r ; i ++ ) arr . push_back ( i ) ; vector < vector < int > > result ; for ( int i : arr ) result . push_back ( { i , func ( i ) } ) ; sort ( result . begin ( ) , result . end ( ) ) ; cout << ( result [ k - 1 ] [ 0 ] ) ; } int main ( ) { int l = 12 ; int r = 15 ; int k = 2 ; findKthElement ( l , r , k ) ; return 0 ; }