尋找兩個數的最小公倍數


在數學中,最小公倍數 (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

更新於:2020 年 6 月 17 日

788 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.