求兩個數字的最小公倍數
在數學中,最小公倍數 (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