N-th multiple in sorted list of multiples of two numbers in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that finds the n-th multiple from the sorted list of two numbers multiples.

You are given three numbers. You need to find the n-th multiple from the multiples of the first two numbers. Let's see an example to understand it more clearly.


x = 2
y = 3
n = 7



Let's see the steps to solve the problem.

  • Find the first n multiples of x and y.
  • Remove the duplicate multiples.
  • Sort the multiples.
  • Get and print the n-th multiple.


Let's see the code.

 Live Demo

using namespace std;
int findNthMultiple(int x, int y, int n) {
   vector<int> multiples;
   for (int i = 1; i <= n; i++) {
      multiples.push_back(x * i);
   sort(multiples.begin(), multiples.end());
   for (int i = 1, k = n; i <= n && k; i++) {
      if (!binary_search(multiples.begin(), multiples.end(), y * i)) {
         multiples.push_back(y * i);
         sort(multiples.begin(), multiples.end());
   return multiples[n - 1];
int main() {
   int x = 2, y = 3, n = 7;
   cout << findNthMultiple(x, y, n) << endl;
   return 0;


f you run the above code, then you will get the following result.



If you have any queries in the tutorial, mention them in the comment section.

Published on 26-Jun-2021 14:10:20