フィルターのクリア

how to calculate GCD in matlab

11 ビュー (過去 30 日間)
DEDEN PRADEKA
DEDEN PRADEKA 2016 年 9 月 10 日
コメント済み: Abdulrehman Khan 2017 年 7 月 24 日
I have variable : A = [1 1 1 1 2 1 3 2]; how calculate greatest common divisor in variable A ?

採用された回答

John D'Errico
John D'Errico 2016 年 9 月 10 日
編集済み: John D'Errico 2016 年 9 月 10 日
Compute the GCD of the first pair of elements. Then just loop. The gcd of more then one number is simply
gcd(gcd(a,b),c)
etc. So the solution is trivial.
d = A(1);
for n = 2:numel(A)
d = gcd(d,A(n));
end
If you cannot use GCD in your code, then you need to do some reading. There are several simple schemes to compute the GCD. The Euclidean algorithm is the simplest. It turns out this is trivial to write in MATLAB.
Start out with some vector A.
A = [12 30 144 20];
Take the smallest element of A, and compute the modulus. Thus, effectively the Euclidean algorithm, applied to a vector of numbers...
d = min(A);
while true
r = mod(A,d);
if ~any(r)
break
end
% find the smallest non-zero element of r
r(r == 0) = inf;
d = min(r);
end
When the loop terminates, which it must do as long as all of the elements of A are positive integers, then d is the GCD of the group.
  1 件のコメント
Abdulrehman Khan
Abdulrehman Khan 2017 年 7 月 24 日
can you explain what does these lines do
r = mod(A,d);
if ~any(r)

サインインしてコメントする。

その他の回答 (1 件)

George
George 2016 年 9 月 10 日
Look here to find the logic of how to calculate the greatest common factor. Then look at the docs for

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by