- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
N-th multiple in sorted list of multiples of two numbers in C++
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.
Input
x = 2 y = 3 n = 7
Output
10
The first n ****multiples of 2 are 2 4 6 8 10 12 14
The first n ****multiples of 3 ****are 3 6 9 12 15 18 21
If combine both multiples and sort them we get 2 3 4 6 8 9 10 12 14 15 18 21 and the nth number from the list is 10.
Algorithm
- Initialise a vector to store all the multiples.
- Find the first n ****multiples of x and add them to the above vector.
- Now, find the first n multiples of y.
- Add them to the vector if it is not already present in the vector.
- Sort the multiples.
- Print the nth multiple from the vector.
Implementation
Following is the implementation of the above algorithm in C++
#include<bits/stdc++.h> 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; }
Output
f you run the above code, then you will get the following result.
10
Advertisements