N | C ++ program to find n - th number in the sorted list of multiples of two numbers . ; Return the n - th number in the sorted list of multiples of two numbers . ; Generating first n multiple of a . ; Sorting the sequence . ; Generating and storing first n multiple of b and storing if not present in the sequence . ; If not present in the sequence ; Storing in the sequence . ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int nthElement ( int a , int b , int n ) { vector < int > seq ; for ( int i = 1 ; i <= n ; i ++ ) seq . push_back ( a * i ) ; sort ( seq . begin ( ) , seq . end ( ) ) ; for ( int i = 1 , k = n ; i <= n && k ; i ++ ) { if ( ! binary_search ( seq . begin ( ) , seq . end ( ) , b * i ) ) { seq . push_back ( b * i ) ; sort ( seq . begin ( ) , seq . end ( ) ) ; k -- ; } } return seq [ n - 1 ] ; } int main ( ) { int a = 3 , b = 5 , n = 5 ; cout << nthElement ( a , b , n ) << endl ; return 0 ; }