目录
1. 基本思想
把数组乘以数次10,直到变成整数数组为止;遍历整数数组的元素,用matlab自带的lcm和gcd函数;求出整数数组的最小公倍数和最大公因数之后再除以相应次数的10
(其实很简单,就是不知道为啥网上没找到相应的函数,就自己速度弄了一个;写得很急,如果发现有中间有什么问题请联系我!)
2. DEMO
array = [0.1, 0.02, 3, 0.25];
lcm = LCM(array);
gcd = GCD(array);
disp(['LCM: ', num2str(lcm)])
disp(['GCD: ', num2str(gcd)]);
运行结果:
3. 计算最小公倍数(LCM)
function result = LCM(array)
n = length(array);
tmp = array;
exp = 0; % Record how many times the array has been multiplied by 10
while ~is_intarray(tmp) % Whether array multiplied by 10's has become integer
tmp = tmp * 10;
exp = exp + 1;
end
result = lcm_array(uint32(tmp),n); % Calculate the LCM of the integer array which has been multiplied by 10's
if (exp > 0) % If the array is multiplied by 10's, divide the LCM by 10's in return
result = double(result) / 10^exp;
end
end
% Calculate the LCM of an integer array
function result = lcm_array(array, n)
result = array(1);
for i = 1:n-1
result = lcm(result,array(i+1));
end
end
这里面用到一个判定被乘了10的数组是否已经变成整数了:
function result = is_intarray(array)
tmp = round(array);
if (abs(array - tmp) < 10^(-10))
result = 1;
else
result = 0;
end
end
4. 计算最大公因数(GCD)
function result = GCD(array)
n = length(array);
tmp = array;
exp = 0; % Record how many times the array has been multiplied by 10
while ~is_intarray(tmp) % Whether array multiplied by 10's has become integer
tmp = tmp * 10;
exp = exp + 1;
end
result = gcd_array(uint32(tmp),n); % Calculate the LCM of the integer array which has been multiplied by 10's
if (exp > 0) % If the array is multiplied by 10's, divide the LCM by 10's in return
result = double(result) / 10^exp;
end
end
% Calculate the GCD of an integer array
function result = gcd_array(array, n)
result = array(1);
for i = 1:n-1
result = gcd(result,array(i+1));
end
end