求两个数字的最小公倍数
在数学中,最小公倍数 (LCM) 是可以被这两个数字整除的最小整数。
可以通过多种方法(例如因子分解等)计算 LCM,但在本算法中,我们使用 1、2、3...n 的值乘以较大的数字,直到找到可以被第二个数字整除的数字。
输入和输出
Input: Two numbers: 6 and 9 Output: The LCM is: 18
算法
LCMofTwo(a, b)
输入: 两个数字 a 和 b,其中 a > b。
输出: a 和 b 的 LCM。
Begin lcm := a i := 2 while lcm mod b ≠ 0, do lcm := a * i i := i + 1 done return lcm End
示例
#include<iostream>
using namespace std;
int findLCM(int a, int b) { //assume a is greater than b
int lcm = a, i = 2;
while(lcm % b != 0) { //try to find number which is multiple of b
lcm = a*i;
i++;
}
return lcm; //the lcm of a and b
}
int lcmOfTwo(int a, int b) {
int lcm;
if(a>b) //to send as first argument is greater than second
lcm = findLCM(a,b);
else
lcm = findLCM(b,a);
return lcm;
}
int main() {
int a, b;
cout << "Enter Two numbers to find LCM: "; cin >> a >> b;
cout << "The LCM is: " << lcmOfTwo(a,b);
}输出
Enter Two numbers to find LCM: 6 9 The LCM is: 18
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP