C++ 中兩個數字的倍數排序列表中的第 N 個倍數
給定三個數字。您需要找到前兩個數字的倍數中的第 n 個倍數。讓我們看一個例子來更清楚地理解它。
輸入
x = 2 y = 3 n = 7
輸出
10
2 的前 n 個倍數是 2 4 6 8 10 12 14
3 的前 n 個倍數是 3 6 9 12 15 18 21
如果將這兩個倍數組合並排序,我們將得到 2 3 4 6 8 9 10 12 14 15 18 21,列表中的第 n 個數字是 10。
演算法
- 初始化一個向量來儲存所有倍數。
- 找到 x 的前 n 個倍數並將它們新增到上述向量中。
- 現在,找到 y 的前 n 個倍數。
- 如果向量中不存在,則將它們新增到向量中。
- 對倍數進行排序。
- 列印向量中的第 n 個倍數。
實現
以下是上述演算法在 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; }
輸出
如果您執行以上程式碼,則將得到以下結果。
10
廣告