C ++中两个数字的倍数排序列表中的第N个倍数
在本教程中,我们将编写一个程序,从两个数字倍数的排序列表中找到第n个倍数。
给你三个数字。您需要从前两个数字的倍数中找到第n个倍数。让我们看一个例子来更清楚地理解它。
输入
x = 2 y = 3 n = 7输出结果
21
让我们看看解决问题的步骤。
找出x和y的前n个倍数。
删除重复的倍数。
对倍数进行排序。
获取并打印第n个倍数。
示例
让我们看看代码。
#include输出结果using namespace std; int findNthMultiple(int x, int y, int n) { vector 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
结论
如果您对本教程有任何疑问,请在评论部分提及。