在 C++ 中不使用 GCD 查找多个(或数组)数字的 LCM
我们有一个数组 A,我们必须不使用 GCD 操作查找所有元素的 LCM。如果数组类似于 {4, 6, 12, 24, 30},则 LCM 将为 120。
两个数字的 LCM 可以轻松计算。我们必须遵循此算法才能获得 LCM。
getLCM(a, b) −
begin if a > b, then m := a, otherwise m := b while true do if m is divisible by both a and b, then return m m := m + 1 done end
使用此函数获取数组前两个数字的 LCM,然后 LCM 的结果将用于查找下一个元素的 LCM,因此我们可以得到结果
示例
#include <iostream>
using namespace std;
int getLCM(int a, int b){
int m;
m = (a > b) ? a : b;
while(true){
if(m % a == 0 && m % b == 0)
return m;
m++;
}
}
int getLCMArray(int arr[], int n){
int lcm = getLCM(arr[0], arr[1]);
for(int i = 2; i < n; i++){
lcm = getLCM(lcm, arr[i]);
}
return lcm;
}
int main() {
int arr[] = {4, 6, 12, 24, 30};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "LCM of array elements: " << getLCMArray(arr, n);
}输出
LCM of array elements: 120
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP