In: Advanced Math
Discrete math
1) Using MatLab (any language is fine just say what language is used).
function d=lemma_gcd(a,b)
%This program will return the greatest common divisor for input
variables a
%and b where a and b are integers such that they are not both 0. It
uses
%Lemma 4.8.3 on page 225.
%Note: gcd(a,b)=gcd(-a,b)=gcd(a,-b)=gcd(-a,-b), so
a=abs(a);
b=abs(b);
%This following section sets up the arrays we will use to store
the
%changing values of our variables as a sequence. "c" will be the
count
%variabe, stored in "C", "a" and "b" will also bechanging and
stored in "A"
%and "B" arrays through the iterations of the loops.
c=0;
C(1)=c; %Stores c=0 in the array, C
%Next find the initial a and b to kick the program into gear
if a==0 & b==0
fprintf('You cannot input these variables\n')
d=inf;
else
if floor(a)~=a
fprintf('You cannot input these variables\n')
d=inf;
if floor(b)~=b
fprintf('You cannot input these variables\n')
d=inf;
end
end
end
MATLAB CODE:-
function d=lemma_gcd(a,b)
%This program will return the greatest common divisor for input variables a
%and b where a and b are integers such that they are not both 0. It uses
%Lemma 4.8.3 on page 225.
%Note: gcd(a,b)=gcd(-a,b)=gcd(a,-b)=gcd(-a,-b), so
a=abs(a);
b=abs(b);
%This following section sets up the arrays we will use to store the
%changing values of our variables as a sequence. "c" will be the count
%variabe, stored in "C", "a" and "b" will also be changing and stored in "A"
%and "B" arrays through the iterations of the loops.
c=0;
C(1)=c; %Stores c=0 in the array, C
%Next find the initial a and b to kick the program into gear
if a==0 & b==0
fprintf('You cannot input these variables\n')
d=inf;
return
else
if floor(a)~=a
fprintf('You cannot input these variables\n')
d=inf;
return
end
if floor(b)~=b
fprintf('You cannot input these variables\n')
d=inf;
return
end
end
% Swap m and n if m less than n
% to allow the algorithm to function properly
if a==0
d=b;
return
end
if b==0
d=a;
return
end
if a < b
tmp = a;
a = b;
b = tmp;
end
% Result of modulus is zero so we have found the gcd
if mod(a,b) == 0
d = b;
else
d = lemma_gcd(b,mod(a,b)); % Euclid's algorithm
end
end