寻找两个数的最小公倍数
在数学中,最小公倍数 (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