中易网

matlab 中 最大公约数的递归程序如何编写

答案:1  悬赏:20  
解决时间 2021-01-15 00:18
  • 提问者网友:杀生予夺
  • 2021-01-14 05:01
matlab 中 最大公约数的递归程序如何编写
最佳答案
  • 二级知识专家网友:玩家
  • 2021-01-14 06:22
matlab有自带的gcd函数来求最大公约数。function [g,c,d] = gcd(a,b)
%GCDGreatest common divisor.
% G = GCD(A,B) is the greatest common divisor of corresponding elements
% of A and B.The arrays A and B must contain integer values and must be
% the same size (or either can be scalar). GCD(0,0) is 0 by convention;
% all other GCDs are positive integers.
%
% [G,C,D] = GCD(A,B) also returns C and D so that G = A.*C + B.*D.
% These are useful for solving Diophantine equations and computing
% Hermite transformations.
%
% Class support for inputs A,B:
%float: double, single
%
% See also LCM.

% Algorithm: See Knuth Volume 2, Section 4.5.2, Algorithm X.
%
% Thanks to John Gilbert
% Copyright 1984-2008 The MathWorks, Inc.
% $Revision: 5.14.4.4 $$Date: 2008/09/13 06:57:21 $classin = superiorfloat(a,b);% Do scalar expansion if necessary
if isscalar(a)
a = a(ones(size(b)));
elseif isscalar(b)
b = b(ones(size(a)));
endif ~isequal(size(a),size(b))
error('MATLAB:gcd:InputSizeMismatch', 'Inputs must be the same size.')
else
siz = size(a);
a = a(:); b = b(:);
endif isNotRealIntegerValue(a) || isNotRealIntegerValue(b)
error('MATLAB:gcd:NonIntInputs', 'Inputs must be real integers.')
endwarnIfGreatThanLargestFlint(a,b,classin);c = zeros(size(a),classin);
d = zeros(size(a),classin);
g = zeros(size(a),classin);
for k = 1:length(a)
u = [1 0 abs(a(k))];
v = [0 1 abs(b(k))];
while v(3)
q = floor( u(3)/v(3) );
t = u - v*q;
u = v;
v = t;
end

c(k) = u(1) * sign(a(k));
d(k) = u(2) * sign(b(k));
g(k) = u(3);
endc = reshape(c,siz);
d = reshape(d,siz);
g = reshape(g,siz);function flag = isNotRealIntegerValue(A)
flag = ~isreal(A) || ~isequal(round(A),A) || any(isinf(A(:)));function warnIfGreatThanLargestFlint(A,B,classCheck)
if strcmp(classCheck,'double')
largestFlint = 2^53-1;
else % single
largestFlint = 2^24-1;
end
if any(abs(A(:)) > largestFlint) || any(abs(B(:)) > largestFlint)
warning('MATLAB:gcd:largestFlint', ...
['Inputs contain values larger than the largest consecutive flint.\n', ...
' Result may be inaccurate.']);
end
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息!
大家都在看
推荐信息