create an lcm function without actually using lcm in matlab

Here's an algorithm that you can use to create a function that calculates the LCM (Least Common Multiple) without using the built-in lcm function in MATLAB:

main.m
function result = mylcm(a, b)
% Returns the LCM of a and b using prime factorization algorithm

% Find prime factors of a
p1 = factor(a);

% Find prime factors of b
p2 = factor(b);

% Combine prime factors of both numbers and remove duplicates
p = unique([p1 p2]);

% Calculate LCM using prime factors
result = 1;
for i = 1:length(p)
    result = result * p(i) ^ max([sum(p1 == p(i)) sum(p2 == p(i))]);
end
end
411 chars
19 lines

This function works by first finding the prime factors of both input numbers (a and b), and then combining them while removing duplicates. The LCM is then calculated by raising each prime factor to the highest power found in either a or b, and multiplying all of the resulting numbers together.

Note that this function assumes that the input arguments a and b are positive integers.

gistlibby LogSnag