LCM seems broken. What am I missing?
15 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
James Brown
el 9 de Sept. de 2023
Editada: Dyuman Joshi
el 9 de Sept. de 2023
Possibly I have missed the obvious or made some other dumb mistake, but I'm trying to find the least common multiple of a vector like this one:
v= [3, 4, 15, 26, 20, 10, 8, 6, 1]
which happens to be 1560 (according to these guys: https://www.calculatorsoup.com/calculators/math/lcm.php )
I have not been able to find any way to input v into lcm and get 1560 or any other number that returns an integer vector when divided by v. In fact the help examples, like this one:
A = [5 17; 10 60];
B = 45;
L = lcm(A,B)
Also do not give results I was expecting, which in this case would be: 3060
Help appreciated and thanks!
0 comentarios
Respuesta aceptada
Dyuman Joshi
el 9 de Sept. de 2023
Editada: Dyuman Joshi
el 9 de Sept. de 2023
"What am I missing?"
You are expecting it to work a particular way.
You looked up an example from the documentation page of lcm, but you did not go through the syntax of the function i.e. what input arguments need to be provided and what is the corresponding output.
> Both the inputs must be of the same size, in which the output is the lcm of respective pairs of the input - C_ij = lcm(A_ij, B_ij)
A = randi([1 10],2,3)
B = randi([11 20],2,3)
C = lcm(A,B)
> One input must be a scalar, in this case, the output is lcm of each element of non-scalar input with the scalar input - C_ij = lcm(A_ij,B)
A = randi(50,3,4)
B = 3
C = lcm(A,B)
One way of finding the lcm of an array of values -
v= [3, 4, 15, 26, 20, 10, 8, 6, 1]
out = 1;
for k=v
out=lcm(out,k);
end
out
8 comentarios
Paul
el 9 de Sept. de 2023
fold using numerical lcm will have the same concerns with accuracy that @James Brown alreay identified, won't it?
The function argument to fold is expected to take two inputs, but if the input v is a scalar then fold just returns the input. For some cases, that might be sensible value, like
[fold(@sum,5) fold(@prod,5)]
But for other cases, such as
fold(@or,5)
returning the input might not be a logical result.
Walter Roberson
el 9 de Sept. de 2023
Yes, if the input values to fold are not symbolic, then fold will have the same accuracy concerns -- although fold is part of the symbolic toolbox, it makes no attempt to convert the datatypes. Basically, it is just a convenient shortcut for a loop -- not unlike arrayfun()
Más respuestas (0)
Ver también
Categorías
Más información sobre Number Theory en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!