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