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 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短