LCM seems broken. What am I missing?
조회 수: 14 (최근 30일)
이전 댓글 표시
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
채택된 답변
Dyuman Joshi
2023년 9월 9일
편집: Dyuman Joshi
2023년 9월 9일
"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
Paul
2023년 9월 9일
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
2023년 9월 9일
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()
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Number Theory에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!