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
结论
如果您对本教程有任何疑问,请在评论部分提及。
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短