C++ 程式,用來求 n 個數的 GCD 和 LCM
這是求 n 個數的 GCD 和 LCM 的程式碼。兩個或多個大於 0 的整數的 GCD 或最大公因子是能同時整除每個整數的最大整數。GCD 也稱為最大公因數。
兩個數的最小公倍數 (LCM) 是既是這兩個數的倍數的最小數(不為零)。
演算法
Begin
Take two numbers as input
Call the function gcd() two find out gcd of n numbers
Call the function lcm() two find out lcm of n numbers
gcd(number1, number2)
Declare r, a, b
Assign r=0
a = (number1 greater than number2)? number1: number2
b = (number1 less than number2)? number1: number2
r = b
While (a mod b not equal to 0)
Do
r = a mod b
a=b
b=r
Return r
Done
lcm(number1, number2)
Declare a
a=(number1 greater than number2)?number1:number2
While(true) do
If
(a mod number1 == 0 and a number2 == 0)
Return a
Increment a
Done
End示例程式碼
#include<iostream>
using namespace std;
int gcd(int m, int n) {
int r = 0, a, b;
a = (m > n) ? m : n;
b = (m < n) ? m : n;
r = b;
while (a % b != 0) {
r = a % b;
a = b;
b = r;
}
return r;
}
int lcm(int m, int n) {
int a;
a = (m > n) ? m: n;
while (true) {
if (a % m == 0 && a % n == 0)
return a;
++a;
}
}
int main(int argc, char **argv) {
cout << "Enter the two numbers: ";
int m, n;
cin >> m >> n;
cout << "The GCD of two numbers is: " << gcd(m, n) << endl;
cout << "The LCM of two numbers is: " << lcm(m, n) << endl;
return 0;
}輸出
Enter the two numbers: 7 6 The GCD of two numbers is: 1 The LCM of two numbers is: 42
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式語言
C++
C#
MongoDB
MySQL
Javascript
PHP