MATLAB计算小数数组的最小公倍数和最大公因数
目录
1. 基本思想
2. DEMO
3. 计算最小公倍数(LCD)
4. 计算最大公因数(GCM)
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. 计算最小公倍数(LCD)
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 integertmp = 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 returnresult = 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-1result = lcm(result,array(i+1));
end
end
这里面用到一个判定被乘了10的数组是否已经变成整数了:
function result = is_intarray(array)
tmp = round(array);
if (abs(array - tmp) < 10^(-10))result = 1;
elseresult = 0;
end
end
4. 计算最大公因数(GCM)
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 integertmp = 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 returnresult = 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-1result = gcd(result,array(i+1));
end
end
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
